Created Object in Python Shell, not recognized when queried - django

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

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)

Related

Django rest framework ```TypeError: type object argument after ** must be a mapping, not int``` being thrown

I have a SMSMessages model that will contain all the sms sent.I'm trying access via the django-rest-framework ListCreateAPIView class, but I keep on hitting error when I try to do an OPTION request on the api via Insomnia, TypeError at /smsmessages/
type object argument after ** must be a mapping, not int.
I searched on SO and found similar errors but they were caused b/c of a filter() argument, which doesn't apply to this.
I'm using django 2.2.5, python 3.6.8, django-rest-framework 3.10.3 and a mysqlclient 1.4.4.
this is the model of SMSMessages
from django.db import models
from django.contrib.auth.models import AbstractUser
from rest_framework.authtoken.models import Token
class SMSMessages(models.Model):
sms_number_to = models.CharField(max_length=14)
sms_content = models.CharField(max_length=160)
sending_user = models.ForeignKey("SMSUser", on_delete=models.PROTECT, related_name="user_that_sent", limit_choices_to=1)
sent_date = models.DateTimeField(auto_now=True)
delivery_status = models.BooleanField(default=False)
class Meta:
verbose_name_plural = "SMSMessages"
def __str__(self):
return self.sending_user
and this is this the urls.py file:
from django.urls import path
from rest_framework.authtoken import views
from rest_framework.routers import DefaultRouter
from notification.apiviews import SMSendView, SMSMessagesView
app_name = "notification"
router = DefaultRouter()
urlpatterns = [
path("smsmessages/", SMSMessagesView.as_view(), name="sms_messages"),
]
so the way I access it is by sending an OPTION request to http://localhost:8000/smsmessages/.
This the SMSMessagesview class that is used for the api view:
from rest_framework import generics, status, viewsets, permissions
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import get_object_or_404, get_list_or_404
from django.contrib.auth import authenticate
from commons.models import SMSMessages
from commons.serializers import SMSMessagesSerializer
class SMSMessagesView(generics.ListCreateAPIView):
"""
This class is responsible for generating, and returning, the view for all created objects of the SMSMessages model.
It sub-classes the ListCreateAPIView class from the generics module.
"""
queryset = SMSMessages.objects.all()
if not queryset:
Response(data={"{0} not found".format(queryset)}, status=404, content_type="application/json")
serializer_class = SMSMessagesSerializer
and this is the error:
TypeError at /notification/smsmessages/
type object argument after ** must be a mapping, not int
Request Method: OPTIONS
Request URL: http://localhost:8055/notification/smsmessages/
Django Version: 2.2.5
Python Executable: /home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/bin/python
Python Version: 3.6.8
Python Path: ['/home/gadd/vscodeworkspace/sms.et/api.sms.et', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python36.zip', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages']
Server time: Sat, 5 Oct 2019 16:19:59 +0000
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_swagger',
'rest_framework.authtoken',
'commons',
'notification']
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 "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
505. response = self.handle_exception(exc)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
465. self.raise_uncaught_exception(exc)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in raise_uncaught_exception
476. raise exc
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
502. response = handler(request, *args, **kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in options
516. data = self.metadata_class().determine_metadata(request, self)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/metadata.py" in determine_metadata
68. actions = self.determine_actions(request, view)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/metadata.py" in determine_actions
94. actions[method] = self.get_serializer_info(serializer)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/metadata.py" in get_serializer_info
111. for field_name, field in serializer.fields.items()
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/utils/functional.py" in __get__
80. res = instance.__dict__[self.name] = self.func(instance)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in fields
360. for key, value in self.get_fields().items():
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in get_fields
1047. source, info, model, depth
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in build_field
1182. return self.build_relational_field(field_name, relation_info)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in build_relational_field
1257. field_kwargs = get_relation_kwargs(field_name, relation_info)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/utils/field_mapping.py" in get_relation_kwargs
255. limit_choices_to = models.Q(**limit_choices_to)
Exception Type: TypeError at /notification/smsmessages/
Exception Value: type object argument after ** must be a mapping, not int
This is the serializer class used:
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from commons.models import SMSUser, SMSPrice, Type, SMSMessages
class SMSMessagesSerializer(serializers.ModelSerializer):
"""
A class for serializing the SMSMessages model's data. It sub-classes the
ModelSerializer class from serializer's module.
"""
class Meta:
model = SMSMessages
fields = '__all__'
This same error is raised when I try to add an SMSMessages object to the db via the admin interface. Can anybody help?
From the documentation for ForeignKey.limit_choices_to, it...
sets a limit to the available choices for this field when this field is rendered using a ModelForm or the admin (by default, all objects in the queryset are available to choose). Either a dictionary, a Q object, or a callable returning a dictionary or Q object can be used.
...but in the model, you set an integer limit_choices_to=1 which is none of these things.
Did you perhaps intend to use something like limit_choices_to={'id': 1} to limit choices to SMS users with that ID?
That's just because you use limit_choices_to with wrong data format which defined by Django.
Either a dictionary, a Q object, or a callable returning a dictionary or Q object can be used.
So this caused the error:
sending_user = models.ForeignKey("SMSUser", on_delete=models.PROTECT, related_name="user_that_sent", limit_choices_to=1 # HERE)
So you might need to be clear what you want to do here to config the right filter so that Django Admin will will filter data when you select sending_user for your model. Like if you want to allow to select is_superuser only for sending_user on admin page then you can go with this:
limit_choices_to={
'is_superuser': True,
}

How to properly include + register viewset routers with Django 2.0 DRF 3.8

I'm developing a basic Django DRF API. I have been using class-based views with explicit URLs. Now I'm trying to use very vanilla DRF ViewSets + router (for auto URL generation).
Can anybody help point me in the right direction? I'm on DRF 3.8 and Django 2.0
Project urls.py:
from django.conf.urls import url, include
urlpatterns = [
url(r'^userprofile/', include('UserProfile.urls', namespace='UserProfile')),
]
App: UserProfile/urls.py:
from django.conf.urls import include
from django.urls import path
from rest_framework.routers import DefaultRouter
from UserProfile import views
app_name = 'UserProfile'
router = DefaultRouter()
router.register('humans', views.HumanViewSet,)
urlpatterns = [path('', include(router.urls))]
App: UserProfile/views.py
from rest_framework import viewsets
from UserProfile.models import Human
from UserProfile.serializers import HumanSerializer
class HumanViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = HumanSerializer
queryset = Human.objects.all()
I get an error:
__init__() missing 2 required positional arguments: 'app_name' and 'app_module'
Full traceback:
Including full traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/userprofile/humans/
Django Version: 2.0.4
Python Version: 3.6.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_framework_simplejwt',
'django_extensions',
'django_pdb',
'django_use_email_as_username.apps.DjangoUseEmailAsUsernameConfig',
'custom_user.apps.CustomUserConfig',
'factory',
'UserProfile']
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 "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
103. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
466. request = self.initialize_request(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in initialize_request
125. request = super(ViewSetMixin, self).initialize_request(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in initialize_request
368. authenticators=self.get_authenticators(),
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in get_authenticators
262. return [auth() for auth in self.authentication_classes]
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in <listcomp>
262. return [auth() for auth in self.authentication_classes]
Exception Type: TypeError at /userprofile/humans/
Exception Value: __init__() missing 2 required positional arguments: 'app_name' and 'app_module'

Django Sitemap and Absolute URL

I have an issue setting up a sitemap with my models. I am getting the following error. Reverse for '5555155555' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []. I think I have to pass a slug to the location but not 100% sure how I would accomplish this task.
#sitemap.py
from django.contrib.sitemaps import Sitemap
from django.contrib.flatpages.models import FlatPage
from django.urls import reverse
from phonenumbers.models import Phone
class PhoneSitemap(Sitemap):
changefreq = "always"
priority = 0.5
def items(self):
return Phone.objects.all()
def location(self, obj):
return reverse(obj)
def lastmode(self, obj):
return obj.created
class FlatpageSitemap(Sitemap):
changefreq = "always"
priority = 0.5
def items(self):
return FlatPage.objects.all()
#models.py
class Phone(models.Model):
phone_number = models.CharField(blank=False, max_length=15) # validators should be a list
name = models.CharField(max_length=50)
message = models.TextField()
caller = models.CharField(max_length=100, choices=CALLER_CHOICES, default="Unknown")
created = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(max_length=250, unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.phone_number)
super(Phone, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('phonenumbers:phone_details', args=[self.slug])
def __str__(self):
return self.phone_number
#urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.flatpages import views
from django.contrib.sitemaps.views import sitemap
from .sitemap import PhoneSitemap, FlatpageSitemap
from info.views import home
sitemaps = {
'posts': PhoneSitemap,
'pages': FlatpageSitemap,
}
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', home, name="home"),
url(r'^privacy-policy/$', views.flatpage, {'url': '/privacy-policy/'}, name='privacy-policy'),
url(r'^terms-and-conditions/$', views.flatpage, {'url': '/terms-and-conditions/'}, name='terms-and-conditions'),
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
url(r'^whocalledme/', include('phonenumbers.urls', app_name="phonenumbers", namespace="phonenumbers")),
]
phonenumbers.urls
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^search/$', views.search_numbers, name="search_numbers"),
url(r'^number/(?P<slug>[-\w]+)/$', views.phone_detail, name="phone_detail"),
url(r'^add_number/$', views.add_number, name='add_number'),
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/sitemap.xml
Django Version: 1.10.4
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.flatpages',
'whitenoise.runserver_nostatic',
'crispy_forms',
'django.contrib.sitemaps',
'phonenumbers']
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 "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/contrib/sitemaps/views.py" in inner
16. response = func(request, *args, **kwargs)
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/contrib/sitemaps/views.py" in sitemap
68. protocol=req_protocol))
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/contrib/sitemaps/__init__.py" in get_urls
105. urls = self._urls(page, protocol, domain)
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/contrib/sitemaps/__init__.py" in _urls
114. loc = "%s://%s%s" % (protocol, domain, self.__get('location', item))
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/contrib/sitemaps/__init__.py" in __get
62. return attr(obj)
File "/Users/Tommy/Desktop/django/info/info/info/sitemap.py" in location
15. return obj.get_absolute_url()
File "/Users/Tommy/Desktop/django/info/info/phonenumbers/models.py" in get_absolute_url
25. return reverse('phonenumbers:phone_details', kwargs={'slug': self.slug})
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/urls/base.py" in reverse
91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/Users/Tommy/Desktop/django/info/lib/python3.5/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
392. (lookup_view_s, args, kwargs, len(patterns), patterns)
Exception Type: NoReverseMatch at /sitemap.xml
Exception Value: Reverse for 'phone_details' with arguments '()' and keyword arguments '{'slug': '2159642387'}' not found. 0 pattern(s) tried: []
The name is phone_detail in urls.py and phone_details (with an "s") in get_absolute_url(). They should both be the same.

userprofile matching query does not exist django facebook error

I am getting the following error after integrating
DoesNotExist at /facebook/connect/
UserProfile matching query does not exist.
Here is my models.py
from django.db import models
from django_facebook.models import FacebookProfileModel
from django.contrib.auth.models import User
class UserProfile(FacebookProfileModel):
user = models.OneToOneField(User)
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
profile, new = UserProfile.objects.get_or_create(user=instance)
ALSO IN MY SETTINGS
AUTH_PROFILE_MODULE = 'kk.UserProfile'
PLEASE HELP!
EDIT
EDIT My traceback
Environment:
Request Method: POST
Request URL: http://localhost:8000/facebook/connect/?facebook_login=1
Django Version: 1.4.2
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django_facebook',
'kk')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django_facebook-4.0.8-py2.7.egg/django_facebook/utils.py" in wrapper
358. response = f(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django_facebook-4.0.8-py2.7.egg/django_facebook/decorators.py" in _wrapped_view
89. get_persistent_graph(request, redirect_uri=current_uri)
File "/usr/local/lib/python2.7/dist-packages/django_facebook-4.0.8-py2.7.egg/django_facebook/api.py" in get_persistent_graph
61. graph = get_facebook_graph(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django_facebook-4.0.8-py2.7.egg/django_facebook/api.py" in get_facebook_graph
181. profile = request.user.get_profile()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py" in get_profile
400. self._state.db).get(user__id__exact=self.id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get
366. % self.model._meta.object_name)
Exception Type: DoesNotExist at /facebook/connect/
Exception Value: UserProfile matching query does not exist.
Either your create_profile signal isn't being fired (is the signal file being imported from somewhere in django machinery?)
Or you have existing users who have yet to run through your new create_profile signal handler.
Posting the traceback always helps.

Does adding a class to models.py ever cause "view does not exist" error?

I was trying to implement a rating system that receives the information that a user submits.
But I was just wondering if it's possible to have two classes in one models file and get Could not import myapp.comments.views.stars. View does not exist in module myapp.comments.views.
In my models file, I have
class CommentWithRating(Comment):
rating = models.IntegerField()
def save(self, *args, **kwargs):
self.content_object.rating.add(score=self.rating, user=self.user, ip_address=self.ip_address)
super(CommentWithRating, self).save(*args, **kwargs)
class Rating(models.Model):
first_name = models.charField(maxlength=30)
last_name = models.charField(maxlength=30)
department = models.charField(maxlength=30)
comment = models.charField(maxlength=10000)
communi_rating = models.IntegerField()
prepar_rating = models.IntegerField()
interact_rating = models.IntegerField()
help_rating = models.IntegerField()
By the way, stars is a html file. Any ideas?
This is my views,
from django.shortcuts import render_to_response, render
from django.http import HttpResponse
from models import CommentWithRating
def stars(request):
return render(request, 'star.html', {'score': ''})
My error message is simply,
Could not import myapp.comments.views.stars. View does not exist in module
myapp.comments.views.
My traceback is,
Environment:
Request Method: GET
Django Version: 1.4
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'registration',
'django.contrib.admin',
'djangoratings')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
101. request.path_info)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
300. sub_match = pattern.resolve(new_path)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
209. return ResolverMatch(self.callback, args, kwargs, self.name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py" in callback
216. self._callback = get_callable(self._callback_str)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py" in wrapper
27. result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py" in get_callable
101. (lookup_view, mod_name))
Exception Type: ViewDoesNotExist at /rating/
Exception Value: Could not import myapp.comments.views.stars. View does not exist in module >myapp.comments.views.`
Yeah, that's definitely possible.
Try doing a
python ./manage.py shell
and then importing the model or view that is giving you the problem. That might end up giving you more useful debugging information.
(from Django views does not exist or could not import)