Django import error: No module named models - django

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.

Related

Created Object in Python Shell, not recognized when queried

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)

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

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

Trying to send parameters

I'm trying to obtain dedicated urls of some products that I have in my shop.html page. I have five products that I named "cards": (Ysera, Neltharion, Nozdormu, Alexstrasza, Malygos). Each card should have a dedicated url (localhost:8000/card/1/, localhost:8000/card/2/, etc). but instead of obtaining that url, django launch me that message:
DoesNotExist at /card/1/ card matching query does not exist.
I imported properly the class model "card" in my views.py, in fact I am justly using card in a filter function to obtain all products in shop.html. please look my views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from dracoin.apps.synopticup.models import card
from dracoin.apps.home.forms import ContactForm,LoginForm
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth import login,logout,authenticate
from django.http import HttpResponseRedirect
def index(request):
return render_to_response('home/index.html',context_instance=RequestContext(request))
def landing(request):
return render_to_response('home/landing.html',context_instance=RequestContext(request))
def shop(request):
tarj = card.objects.filter(status=True)
ctx = {'tarjetas':tarj}
return render_to_response('home/shop.html',ctx,context_instance=RequestContext(request))
def singleCard(request,id_tarj):
tarj = card.objects.get(id=id_tarj)
ctx = {'card':tarj}
return render_to_response('home/singleCard.html',ctx,context_instance=RequestContext(request))
here my urls.py:
url(r'^card/(?P<id_tarj>.*)/$','dracoin.apps.home.views.singleCard',name='vista_single_card'),
My imported model:
class card(models.Model):
nombre = models.CharField(max_length=100)
descripcion = models.TextField(max_length=300)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.nombre
My singleCard.html:
{% extends 'base.html' %}
{% block title %} Tarjeta {{card.nombre}} {% endblock %}
{% block content %}
<h1>{{ card.nombre }}</h1><br>
<p> {{ card.descripcion }}</p>
{% endblock %}
I don't know if I have a wrong refering "card" class. But I try to apply other answers in this forum. For example:
In Django, how do I objects.get, but return None when nothing is found?
matching query does not exist Error in Django
Django error - matching query does not exist
I don't know if I commit a mistake applying these solutions. Including I try:
tarj = card.objects.filter(id=id_tarj)
Using this I obtain a blank page of my website...
apologizeme in advance my extensive question and if I overlook something.
Thanks!!
Answering to wolendranh I have an urls.py by app and the main urls.py.
Recently I'm learning django by my side and I can't understand how I can define my own consistent identifier in this case.
if it is still useful I put here a traceback generated with the error:
Environment:
Request Method: GET
Request URL: http://localhost:8000/card/1/
Django Version: 1.7
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dracoin.apps.synopticup',
'dracoin.apps.home')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'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')
Traceback:
File "/home/draicore/project/multilevel/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/draicore/project/dracoin/dracoin/apps/home/views.py" in singleCard
24. tarj = card.objects.get(id=id_tarj)
File "/home/draicore/project/multilevel/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
92. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/draicore/project/multilevel/local/lib/python2.7/site-packages/django/db/models/query.py" in get
357. self.model._meta.object_name)
Exception Type: DoesNotExist at /card/1/
Exception Value: card matching query does not exist.
excuse me for prolong this question.
As karthikr says in the comment, you don't have a card with id=1.
This is probably because you previously deleted and recreated a card. The id is an autoincrement field, which means the database does not reuse IDs that have been deleted. If you want your item to have a consistent identifier which you can always use to query it in the URL, you should probably define that as an explicit IntegerField (using another name than id), and query against that instead. Even better, use a slug rather than a numeric ID.
I have few things to clarify:
1. Do you have a single urls.py file in your project? or separate for every app.
If you have a separate like "your_project/card/urls" and it is included into main urls.py you should NOT use "card/" in your url. Because Django already knows that request is for that app.
r'^card/(?P<id_tarj>.*)/$' -> r'^(?P<id_tarj>.*)/$'
If it is in main urls.py try to replace:
r'^card/(?P<id_tarj>.*)/$'
to
r'^card/(?P\d+))/$'
P.s.: I don't have anough reputation for comments, so I added an answer. Sorry.

unbound method must be called with instance as first argument

I'm working with django and i'm getting this error: "unbound method create() must be called with SocialUrl instance as first argument (got nothing instead)". I've read several answers to the same problem here but i'm not sure they are doing the same thing wrong as i am.
Here is the Model containing the method i'm trying to call:
from django.db import models
class SocialUrl(models.Model):
code = models.CharField(max_length=30)
def create():
socialUrl = SocialUrl(code = generateCode())
socialUrl.save()
return socialUrl
def __unicode__(self):
return self.code
and here is the method trying to call SocialUrl.create():
from django.shortcuts import render
from django.template import RequestContext
from .general import generateCode
from .models import SocialUrl
def test(request):
socialUrl = SocialUrl.create()
#print(SocialUrl.objects.all())
return render(request, 'test.html', RequestContext(request, {"title": socialUrl.code}))
Here is the stacktrace:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/su/asdadsf
Django Version: 1.6.2
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'SocialUrl')
Installed Middleware:
('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:\Users\Sverker\.virtualenvs\coomba\lib\site- packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Sverker\Dropbox\Coomba\SbrgCoomba\SocialUrl\views.py" in test
8. socialUrl = SocialUrl.create()
Exception Type: TypeError at /su/asdadsf
Exception Value: unbound method create() must be called with SocialUrl instance as first argument (got nothing instead)
Help would be appreciated :)
You need to instantiate the class before calling a method on the class. Change your view to:
from django.shortcuts import render
from django.template import RequestContext
from .general import generateCode
from .models import SocialUrl
def test(request):
socialUrl = SocialUrl()
socialUrl.create()
#print(SocialUrl.objects.all())
return render(request, 'test.html', RequestContext(request, {"title": socialUrl.code}))
Notice how you instantiate the object first (socialUrl = SocialUrl()) then you run create on the object you've instantiated. (socialUrl.create()).
However, I'm not sure your create method is going to work as you intend. What are you trying to accomplish with the create method?
EDIT to address comments:
I'm not familiar with Java static methods, but I think the standard way to what you want to do is as follows:
First, define your model as you've done. Note that I removed the create method.
from django.db import models
class SocialUrl(models.Model):
code = models.CharField(max_length=30)
def __unicode__(self):
return self.code
Then, in your views, instantiate a model and populate it with the attributes you want.
from django.shortcuts import render
from django.template import RequestContext
from .general import generateCode
from .models import SocialUrl
def test(request):
my_code = generateCode()
socialUrl = SocialUrl()
socialUrl.code = my_code # Setting code attribute to the result of your generateCode function
socialUrl.save() # Saves instance of SocialUrl to database.
return render(request, 'test.html', RequestContext(request, {"title": socialUrl.code}))

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)