Django: unbound method is_authenticated() must be called with AbstractBaseUser instance - django

This issue is rather strange. Here's a stack trace:
Environment:
Request Method: GET
Request URL: http://localhost/en/dashboard
Django Version: 1.9.6
Python Version: 2.7.12
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django_mongoengine',
'django_mongoengine.mongo_auth',
'django_mongoengine.mongo_admin.sites',
'django_mongoengine.mongo_admin',
'django_adyen',
'spiral_api',
'rest_framework',
'rest_framework_mongoengine',
'spiral_admin',
'rest_framework_docs')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'spiral_api.middlewares.BehalfUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'spiral_api.middlewares.AuthHeaderMiddleware')
Traceback:
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
235. response = middleware_method(request, response)
File "/code/django_app/spiral_api/middlewares.py" in process_response
11. def process_response(self, request, response):
File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py" in inner
204. self._setup()
File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py" in _setup
351. self._wrapped = self._setupfunc()
File "/code/django_app/spiral_api/middlewares.py" in get_user
18. user = get_user_middleware(request)
Exception Type: TypeError at /en/dashboard
Exception Value: unbound method is_authenticated() must be called with AbstractBaseUser instance as first argument (got nothing instead)
Here's a middleware:
from functools import partial
from django.contrib.auth.middleware import get_user as get_user_middleware
from django.contrib.auth.models import AbstractBaseUser
from django.utils.functional import SimpleLazyObject
from spiral_api.models import SpiralUserProfile
class AuthHeaderMiddleware(object):
def process_response(self, request, response):
response['is_login'] = int(request.user.is_active) if hasattr(request, 'user') else 0
return response
class BehalfUserMiddleware(object):
def get_user(self, request):
user = get_user_middleware(request)
if user.is_authenticated():
profile = SpiralUserProfile.objects.get(user=user)
return profile.behalf or user
else:
return user
def process_request(self, request):
assert hasattr(request, 'session'), (
"The Django authentication middleware requires session middleware "
"to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
"'django.contrib.sessions.middleware.SessionMiddleware' before "
"'django.contrib.auth.middleware.AuthenticationMiddleware'."
)
request.user = SimpleLazyObject(partial(self.get_user, request))
request.behalf = SimpleLazyObject(lambda: get_user_middleware(request))
Sadly project is not mine. From exception you see it points to get_user_middleware() function. I've tried to add print in there, also as sys.exit(), nothing works.. it seems to be it doesn't even come to that function. Here's how middleware setup looks in Settings:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
'spiral_api.middlewares.BehalfUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'spiral_api.middlewares.AuthHeaderMiddleware'
)
Also a model SpiralUserProfile has a field behalf which is reference to model User. I'm completely puzzled why exception shows error in a place where interpreter doesn't even come to? How to solve this issue?
Versions of requirements.txt:
nose==1.3.7
pinocchio==0.4.2
django_nose==1.4.4
bjoern==1.4.3
amqp==1.4.9
anyjson==0.3.3
apiclient==1.0.3
billiard==3.3.0.23
blinker==1.4
build==1.0.2
celery==3.1.23
Django==1.9.6
django-bootstrap3==7.0.1
django-crispy-forms==1.6.0
django-fanout==1.1.1
django-filter==0.13.0
git+https://github.com/MongoEngine/django-mongoengine
django-redis==4.4.3
django-rest-framework-mongoengine==3.3.0
djangorestframework==3.3.3
drfdocs==0.0.9
EasyProcess==0.2.2
fanout==1.2.0
git+http://github.com/google/google-api-python-client/
gunicorn==19.3.0
httplib2==0.9.2
kombu==3.0.35
mongodbforms==0.3
mongoengine==0.10.6
nltk==3.2.1
oauth2==1.9.0.post1
oauth2client==2.1.0
oauthlib==1.1.2
Pillow==3.2.0
psycopg2==2.6
pubcontrol==2.2.7
pyasn1==0.1.9
pyasn1-modules==0.0.8
PyInvoice==0.1.7
PyJWT==1.4.0
pymongo==3.2.2
python-openid==2.2.5
pytz==2016.4
PyVirtualDisplay==0.2
qrcode==5.3
qrplatba==0.3.4
redis==2.10.5
reportlab==3.3.0
requests==2.10.0
requests-oauthlib==0.6.1
rsa==3.4.2
selenium==2.53.2
simplejson==3.8.2
six==1.10.0
uritemplate==0.6
urllib3==1.15.1
xvfbwrapper==0.2.8
zope.dottedname==4.1.0
pyPdf

I am not sure how this ever worked, but I can see why you'd get that error. In django-mongoengine/mongo_auth/models.py I see this:
class BaseUser(object):
is_anonymous = AbstractBaseUser.is_anonymous
is_authenticated = AbstractBaseUser.is_authenticated
class User(BaseUser, document.Document):
...
which seems to be the source of the error.
You can make it work by modifying that library so that the User class implements those methods directly:
class User(document.Document):
...
def is_anonymous(self):
"""
Always returns False. This is a way of comparing User objects to
anonymous users.
"""
return False
def is_authenticated(self):
"""
Always return True. This is a way to tell if the user has been
authenticated in templates.
"""
return True

Related

Middleware not executed by Django

I am trying to include a middleware in a Django project, but it seems the middleware is not being executed by Django. The idea is to impersonate another user account when having app-administrator privileges.
The MIDDLEWARE section of my settings.py file looks like this:
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',
'mird_project.monitor.middleware.impersonateMiddleware.ImpersonateMiddleware',
]
The middleware class looks like this:
from .models import Usuario
class ImpersonateMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
def process_request(self, request):
us_obj = Usuario.objects.all().filter(id_usuario=request.user.username).first()
tipo = us_obj.tipo.id_tipo
if tipo == "AD" and "__impersonate" in request.GET:
request.session['impersonate_id'] = request.GET["__impersonate"]
elif "__unimpersonate" in request.GET:
del request.session['impersonate_id']
if tipo == "AD" and 'impersonate_id' in request.session:
request.user = Usuario.objects.get(id_usuario=request.session['impersonate_id'])
return None
I inserted an assert False, request inside the process_request method so that it would abort execution with an exception and show me what request contained. It never even got executed, so I assume the middleware never gets executed. It doesn't throw any kind of error and the impersonation mechanism just displays the same administrator user in the site.
Any ideas why the middleware isn't being called?
It looks like you are mixing old and new style middleware APIs. The process_request() method is pre-Django 1.10 and won't get called automatically unless your middleware class uses MiddlewareMixin.
You'll need to call process_request() yourself from the __call__() method:
def __call__(self, request):
self.process_request(request) # Call process_request()
response = self.get_response(request)
return response
Or alternatively you could inherit from MiddlewareMixin so that process_request() is called by Django. However it would only make sense to do that if you need to make the middleware backwards compatible.

url token authentication is failing to authenticate user

I'm failing to authenticate my user upon the registration. I've found out the solution for one time link token authentication, was tampering with ModelBackend you can see the basic solution here, I'll paste up my implementation because I'm using CBV for the view.
Custom ModelBackend:
from django.contrib.auth.backends import ModelBackend
import logging
from business_accounts.models.my_user import MyUser
logger = logging.getLogger(__name__)
class UrlTokenBackend(ModelBackend):
"""
Custom login backend that will accept token allow click url login
"""
def authenticate(self, request, token=None):
try:
user = MyUser.objects.get(token=token)
except MyUser.DoesNotExist:
logger.warning('My user=%s does not exist', user)
return None
if not user.is_active:
return None
def get_user(self, user_id):
try:
return MyUser.objects.get(pk=user_id)
except MyUser.DoesNotExist:
logger.warning('User with this id=%s does not exists', user_id)
return None
The authentication middleware is registered here
AUTHENTICATION_BACKENDS = (
'business_accounts.backends.UrlTokenBackend',
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
)
Custom view is:
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect
from django.views.generic import View
class UrlGatewayLogin(View):
def get(self, request):
token = request.GET.get('token')
user = authenticate(token=token)
login(request, user)
return redirect('dashboard')
and the url is
url(r'^auth/login/', UrlGatewayLogin.as_view(), name='auth-login')
Now I'll construct a url for the login, like so, http:/localhost:8000/auth/login/?token=12323344 so the whole process will just login the user over this link and redirect him to the dashboard.
The login is showing me this error:
Environment:
Request Method: GET
Request URL: http://localhost:8888/auth/login/?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MjYzNjE5MTksInVzZXJfaWQiOjcwLCJlbWFpbCI6ImFkbWluQGFkbWluLmFpIiwidXNlcm5hbWUiOiJhZG1pbkBhZG1pbi5haSIsIm9yaWdfaWF0IjoxNTI2MzU4OTE5fQ.qyR5SYZ1uO0reVSRjcFdXGGhgfKhdu1eU277UAGU5l8
Django Version: 1.8.5
Python Version: 3.4.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.twitter',
'allauth.socialaccount.providers.foursquare',
'allauth.socialaccount.providers.google',
'rest_framework',
'rest_framework_swagger',
'django_filters',
'corsheaders',
'gunicorn',
'googleads',
'django_nose',
'webpack_loader',
'common',
'business_accounts',
'search',
'platforms_search',
'locations',
'reviews',
'socialmedia',
'inbox',
'stats',
'usermanagement',
'connect',
'dashboard',
'freetrial',
'billing',
'demo',
'social_tickets',
'external',
'test_account']
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware')
Traceback:
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/srv/bspotted.net/app/business_accounts/views/url_gateway_login.py" in get
10. login(request, user)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/contrib/auth/__init__.py" in login
111. request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
File "/srv/bspotted.net/venv/lib/python3.4/site-packages/django/utils/functional.py" in inner
226. return func(self._wrapped, *args)
Exception Type: AttributeError at /auth/login/
Exception Value: 'AnonymousUser' object has no attribute '_meta'
So can someone explain why is this happening and how can I overcome this, thank you.
authenticate() should return user object:
class UrlTokenBackend(ModelBackend):
"""
Custom login backend that will accept token allow click url login
"""
def authenticate(self, request, token=None):
try:
user = MyUser.objects.get(token=token)
except MyUser.DoesNotExist:
logger.warning('My user=%s does not exist', user)
return None
if not user.is_active:
return None
return user

Issue with Django 2.0 : 'WSGIRequest' object has no attribute 'session'

I upgraded my Django version from 1.11.5 to 2.0 and I'm trying to solve different deprecated element.
However, even if my CSS/bootstrap style sheet doesn't work, I don't overcome to log into my Django software. I have this issue :
'WSGIRequest' object has no attribute 'session'
This is the entire Traceback :
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/Authentification/Login/
Django Version: 2.0
Python Version: 3.6.2
Installed Applications:
['Institution',
'django.conf.urls',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrapform',
'django_countries',
'chartit',
'Configurations',
'Home',
'Authentication',
'Identity',
'rest_framework',
'Fiscal',
'bootstrap4']
Installed Middleware:
[]
Traceback:
File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/Users/valentinjungbluth/Desktop/Django/DatasystemsCORE/DatasystemsCore/DatasystemsCORE/Authentication/views.py" in Login
26. login(request, user)
File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in login
130. if SESSION_KEY in request.session:
Exception Type: AttributeError at /Authentification/Login/
Exception Value: 'WSGIRequest' object has no attribute 'session'
In my Authentification app :
# views.py file
#-*- coding: utf-8 -*-
from django.contrib.auth import authenticate, login, logout
from .forms import ConnexionForm
from django.shortcuts import render, reverse, get_object_or_404, redirect
from django.http import HttpResponseRedirect, HttpResponse
from .models import LoggedUsers
from API_GED import Logger
import datetime
from django.views.decorators.csrf import csrf_exempt,csrf_protect
#csrf_exempt
def Login(request):
error = False
if request.method == "POST":
form = ConnexionForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password) # Nous vérifions si les données sont correctes
if user: # Si l'objet renvoyé n'est pas None
login(request, user)
response = redirect('Homepage')
return response
else: # sinon une erreur sera affichée
error = True
else:
form = ConnexionForm()
return render(request, 'Authentication_Homepage.html', locals())
def Logout(request):
logout(request)
return redirect(reverse('Choice'))
def ConnectedUsers(request) :
logged_users = LoggedUsers.objects.all()
print (logged_users)
logged_users_number = LoggedUsers.objects.all().count()
context = {
"logged_users":logged_users,
"logged_users_number":logged_users_number,
}
return render(request, "Authentication_LoggedUsers.html", context)
An my models.py file :
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in, user_logged_out
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# avatar = models.ImageField(upload_to='/images/')
class LoggedUsers(models.Model):
user = models.ForeignKey(User, primary_key=True, on_delete=models.CASCADE)
def __str__(self):
return '{}{}{}'.format(self.user.first_name + " ", self.user.last_name + " (", self.user.username + ")")
def login_user(sender, request, user, **kwargs):
LoggedUsers(user=user).save()
def logout_user(sender, request, user, **kwargs):
try:
u = LoggedUsers.objects.get(user=user)
u.delete()
except LoggedUsers.DoesNotExist:
pass
user_logged_in.connect(login_user)
user_logged_out.connect(logout_user)
In my settings.py file, I have MIDDLEWARE_CLASSES :
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.gzip.GZipMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'DatasystemsCORE.middleware.OnlineNowMiddleware',
]
Any idea ?
EDIT :
I wrote MIDDLEWARE like this :
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',
]
It seems to work !
So the MIDDLEWARE_CLASSES changed to MIDDLEWARE https://docs.djangoproject.com/en/2.0/topics/http/middleware/#activating-middleware
MIDDLEWARE_CLASSES has been deprecated since Django 1.10 and was removed completely in version 2.0. That means you have no middleware at all.
You should use the MIDDLEWARE setting instead; note, that uses new-style middleware, you might need to upgrade your custom middleware class.

Django import error: No module named models

I keep receiving the error Could not import movies.views. Error was: No module named models
Here is my traceback:
Environment:
Request Method: GET
Request URL: http://localhost:8000/movies/awesome-movie/
Django Version: 1.3.1
Python Version: 2.7.3
Installed Applications:
['django.contrib.auth',
'username_patch',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.flatpages',
'south',
'tagging',
'tagging_autocomplete',
'accounts',
'movies',
'tracking',
'djcelery',
'pagination']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'pagination.middleware.PaginationMiddleware')
Traceback:
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
101. request.path_info)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
158. return ResolverMatch(self.callback, args, kwargs, self.name)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in _get_callback
167. raise ViewDoesNotExist("Could not import %s. Error was: %s" % (mod_name, str(e)))
Exception Type: ViewDoesNotExist at /movies/awesome-movie/
Exception Value: Could not import movies.views. Error was: No module named models
I am not sure why I have this error. My code is as follows...
I have an django app called tracking and another called movies. I have a python file called tracking.py in the tracking app it consists of the following code:
filmlibrary/tracking/tracking.py
from movies.models import Movie
from tracking.models import MovieView
import os
import base64
def tracking_id(request):
try:
return request.session['tracking_id']
except KeyError:
request.session['tracking_id'] = base64.b64encode(os.urandom(36))
return request.session['tracking_id']
def log_movie_view(request, movie):
t_id = tracking_id(request)
try:
v = MovieView.objects.get(tracking_id=t_id, movie=movie)
v.save()
except MovieView.DoesNotExist:
v = MovieView()
v.movie = movie
v.ip_address = request.META.get('REMOTE_ADDR')
v.tracking_id = t_id
v.user = None
if request.user.is_authenticated():
v.user = request.user
v.save()
The above is pretty basic stuff. My views.py in my movies app uses the tracking.py file here:
filmlibrary/movies/views.py
#login_required
def movie_details(request, slug, template_name="movies/movie_detail.html"):
movie = get_object_or_404(Movie, slug=slug)
movie.tracking_id = tracking.tracking_id(request)
movie.save()
tracking.log_movie_view(request, movie)
context = RequestContext(request, {'movie': movie })
if movie:
try:
screener = movie.moviemedia_set.get(movie_type='screener')
.... continued
UPDATE:
Here are the contents of filmlibrary/tracking/models.py
from django.db import models
from django.contrib.auth.models import User
from movies.models import Movie
class PageView(models.Model):
class Meta:
abstract = True
date = models.DateTimeField(auto_now=True)
ip_address = models.IPAddressField()
user = models.ForeignKey(User, null=True)
tracking_id = models.CharField(max_length=50, default='')
class MovieView(PageView):
movie = models.ForeignKey(Movie)
The error appears to come from the import line from tracking.models import MovieView in the tracking.py file and I am not sure why. As soon as I comment out that line the error goes away but then of course I'll have new errors about MovieView not existing as expected. I don't see anything wrong with that import line in tracking.py.
Does anyone have any suggestions as to why I receive that error and how I can resolve this?
Can you try
from models import MovieView
instead of
from tracking.models import MovieView
The reason being both models.py and tracking.py are in the same app folder "tracking", you don't need to write tracking.models, this will make Django think that you have a folder named models inside the tracking directory.
Though this is a good solution in some cases, this error can also be caused by app name conflicts with built in apps.
I know that our team has encountered this error and it was because of the actual app name. This is also important to note, because you won't be able to pull in models to other apps if that is the case.
#You cannot use this format out of scope
from models import Test
#You can use this both in and out of scope in Django
from myapp.models import Test
If the second example isn't working in your Django project you may be using a conflicting app name. Good examples of unusable built in apps include (but are not limited to) "tests", and "admin".
I would caution against a bandaid fix and investigate your app name closely.

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)