1

Currently creating a Django site for some work I'm doing. Here are the relevant code blocks:

portal/device_categories/models.py

from django.db import models

# Create your models here.
class Type(models.Model):
    device_category = models.CharField(max_length=20)   

def __str__(self):
    return self.device_category

class Device(models.Model):
    category = models.ForeignKey(Type, on_delete=models.CASCADE)
    tms_code = models.CharField(max_length=5)
    device_name = models.CharField(max_length=30)
    device_count = models.CharField(max_length=3)

    def __str__(self):
        return "Device:" + self.device_name

portal/device_categories/urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<device_type>[A-Za-z]+)/$', views.deviceList, name='deviceList'),
]

portal/device_categories/views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Type, Device
from django.template import loader

# Create your views here.
def index(request):
    return HttpResponse("This is the Device Categories Page")

def deviceList(request, device_type):
    all_devices = Device.objects.get(category__device_category=device_type)
    template = loader.get_template('device_categories/index.html')
    context = {
        'all_devices': all_devices,
    }
    return render(request, template, context)

I have created numerous Device Objects using the:

python manage.py shell

methodology, some example categories are: fans, switches, modules. All the categories have also been set up as their own Type Class. Now I have 5 objects that I assigned a category of fans, but when I try to go to url:

127.0.0.1:8000/device_categories/fans/

I am getting error:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/device_categories/fans/

Django Version: 1.11.4
Python Version: 3.6.0
Installed Applications:
['network_resources.apps.NetworkResourcesConfig',
 'device_categories.apps.DeviceCategoriesConfig',
 'device_inventory.apps.DeviceInventoryConfig',
 'on_call.apps.OnCallConfig',
 'contact_info.apps.ContactInfoConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\users\wskidmor\Django\nocportal\device_categories\views.py" in deviceList
  11.     all_devices = Device.objects.get(category__device_category=device_type)

File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\db\models\manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\db\models\query.py" in get
  380.                 self.model._meta.object_name

Exception Type: DoesNotExist at /device_categories/fans/
Exception Value: Device matching query does not exist.

I have verified that the objects exist when I go into the shell so I'm not sure what I'm doing wrong. I have found similar questions posted on here but I have tried those solutions and they unfortunately didn't apply. Thank you for your help

1 Answers1

3

Change this line in your views:

all_devices = Device.objects.get(category__device_category=device_type)

To:

all_devices = Device.objects.filter(category__device_category=device_type)
tdsymonds
  • 1,679
  • 1
  • 16
  • 26
  • 1
    That's right, but I don't think it's causing the error, as the exception is `DoesNotExist`, no? – Paulo Almeida Aug 17 '17 at 16:21
  • thank you so much, I gave you a check for answering it! However, now when I run it, it's not displaying devices with the "fans" category. Is there something else I need to do besides creating objects in the shell? Thanks again @tdsymonds! – nuckingfut5 Aug 17 '17 at 16:31
  • 2
    No worries. What happens in the shell when you run `Device.objects.filter(category__device_category='fans')`? Do you get any results? Are you sure there's not a typo somewhere? Do you get a category if you do `Type.objects.get(device_category='fans')`? – tdsymonds Aug 17 '17 at 16:36
  • This is so frustrating, when I run: `Device.objects.filter(category__device_category='fans')` I get an empty QuerySet, and when I run: `Type.objects.get(device_category='fans')` I get an error that the category doesn't exist so I'm clearly doing something wrong. Do I need to recreate the objects every time I runserver? I checked in the admin of the url and I can see the objects I created so I'm kind of stumped. Thanks again for all your help – nuckingfut5 Aug 17 '17 at 16:49
  • 2
    Did you save the objects in the shell after you created them? What can you see in the Django Admin panel? Why don't you just create through there? Try running in the shell `[t.device_category for t in Type.objects.all()]` and you should get a list of all the type names? If you get no results in the list then you have no `Type` objects. If you do get results then check there's a fans object and the spelling – tdsymonds Aug 17 '17 at 16:56
  • when i type `[t.device_category for t in Type.objects.all()]` in the shell it gives me all the types: `['Supervisors', 'Modules', 'Switches', 'PowerSupplys', 'Fans']` any ideas? Sorry for spamming you with all these questions – nuckingfut5 Aug 17 '17 at 17:09
  • 1
    Fans has a capital F, its case sensitive! – tdsymonds Aug 17 '17 at 17:10
  • I would switch to chat to not create an extended discussion but i dont have enough reputation. I tried doing uppercase Fans a while ago and the url automatically switches it to lowercase 'fans' – nuckingfut5 Aug 17 '17 at 17:12
  • 1
    Then change your views so the filter isn't case sensitive: `all_devices = Device.objects.filter(category__device_category__iexact=device_type)` – tdsymonds Aug 17 '17 at 17:14
  • That worked, thank you so much @tdsymonds!! I really appreciate it!! – nuckingfut5 Aug 17 '17 at 17:18