I'm getting a weird error and I can't track it down. The stack trace doesn't give any clue as to the location of the error either. It's just giving me the standard urlresolvers.py ViewDoesNotExist exception. Here is the error message:
Could not import myapp.myview.views. Error was: No module named model
At first I thought I forgot to put an "s" on models somewhere in my code, but after a search of the entire codebase, that is not the case.
Here's the trackback:
File "C:\Python25\Lib\site-packages\django\core\handlers\base.py" in get_response
91. request.path_info)
File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py" in resolve
216. sub_match = pattern.resolve(new_path)
File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py" in resolve
216. sub_match = pattern.resolve(new_path)
File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py" in resolve
216. sub_match = pattern.resolve(new_path)
File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py" in resolve
123. return self.callback, args, kwargs
File "C:\Python25\Lib\site-packages\django\core\urlresolvers.py" in _get_callback
132. raise ViewDoesNotExist("Could not import %s. Error was: %s" % (mod_name, str(e)))
Exception Value: Could not import myapp.myview.views. Error was: No module named model
From what you've posted, it seems like the error is in myapp.myview.views.
You already mentioned looking for misspellings of "models", which is good. You might also try asking Django to validate your models to ensure that they are properly importable (run this in your Django project root):
python manage.py validate
Beyond that, just keep following the imports in myapp.myview.views until you see something odd. You can check to see if everything is properly importable by opening a shell:
python manage.py shell
And attempting to import and/or try things from there.
Beyond that, someone may be able to assist you more if you post the full traceback. Good luck!
I have been having the same error, and I solved my problem. If you have a forms.py, ensure that all your forms fields are valid. For some reason, if your forms.py file has form field errors, then it causes this exception.
So myapp/myview/views.py imports model and fails. What does the import statement look like?
You can check to see if everything is properly importable by opening a shell:
python manage.py shell
That creates a running environment just as the same as where there is request and response. I believe you can get light on this question if you do it, because I have ever got it and managed it.
Good luck with you.
For me, the view that couldn't be imported had a bad decorator call. Try commenting out the decorator.
##login_required(login_url=reverse('bad!'))
def view_name(request):
Specifically the reverse is failing. Changing it to
#login_required(login_url='http://usatoday.com')
def view_name(request):
works. But, strangely enough, this one url doesn't work:
#login_required(login_url='http://foxnews.com')
def view_name(request):
(yes that's a joke)
I just discovered I should be using reverse_lazy, so this is the ultimate solution:
#login_required(login_url=reverse_lazy('bad!'))
def view_name(request):
Strange this would cause a ViewDoesNotExist error.
I had a similar error:
It was urls.py of the app.
I forgot to add '' in the starting of urlpatterns
SOLUTION:
just add '', to the urlpatterns
from django.conf.urls import patterns,include,url
urlpatterns = patterns('',
url(r'^profile<url name>/$','userprofile.views.user_profile<location of view>'),
)
Related
I have found a strange bug in my Django application. I have a view accessible on /people/<pk>. In tests it works just fine, but in production I have stumbled over a bug at several (just a few!) pk's: Reverse for 'single-person' with arguments '('',)' not found. 1 pattern(s) tried: ['people/(\\d+)/?$']. Since I couldn't catch it with my tests, I'd like to create another test, with the current state of the database, to debug. Also, to prevent future situations like this, I'd always like to be able to run my tests with a copy of the production database, to minimize the chances something goes wrong with the actual data.
I thought it would be as straightforward as
manage.py dumdata --output db-test.json
and then
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test import Client
from people.models import Person
class TestPeopleWithMyData(StaticLiveServerTestCase):
fixtures = ['db-test.json']
def setUp(self):
self.client = Client()
self.client.force_login(user='test_user')
def test_person(self):
for person in Person.objects.all():
print('Testing %s: ' % person, end='')
r = self.client.get('/people/%d' % person.pk)
print(r)
...
However this attempt fails:
======================================================================
ERROR: setUpClass (people.tests.test_my_data.TestPeopleWithMyData)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/username/Documents/python_projects/project/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 178, in __get__
rel_obj = getattr(instance, self.cache_name)
AttributeError: 'Person' object has no attribute '_added_by_cache'
(I have a field named added_by in my Person model.) And then it goes on to say django.contrib.auth.models.DoesNotExist: Problem installing fixture '/Users/username/Documents/python_projects/project/db-test.json': User matching query does not exist.
Since I know that this exactly database works just fine, it doesn't look right to me. So before I dive into debugging this problem, I would like to understand if what I am doing is maybe fundamentally wrong and I shouldn't be able to create test fixtures just like that. Or am I missing some simple mistake?
I think you need to do before running test
python manage.py makemigrations
python manage.py migrate
In your fixture file you have '_added_by_cache' that's not in your model.
I have simple code that basically looks like this:
from django.shortcuts import redirect
def my_view(request):
... does stuff
return redirect('/some_other_url/')
The exception being thrown is "Could not import django.views.generic.simple.redirect_to. Parent module django.views.generic.simple does not exist." When I comment out the "return redirect" code (and replace with return HttpResponse("")) I no longer get the error.
stack trace: NO Longer availalbe because it was posted outside SO http://dpaste.com/1007500/
I just upgraded from django 1.3.1 to django 1.5. Checking the documentation for 1.5 it looks like I should still be able to use "redirect()". I could not find any answers to this from several google searches so hopefully its not some blind oversight on my part.
Looks like problem not in django.shortcuts.redirect, but in view, that process url you were redirected to. According to your traceback, view, that process url 127.0.0.1:8000/post_station/ use somewhere django.views.generic.simple.redirect_to. In django 1.5 you problably shouldn't do it. Use django.views.generic.RedirectView insead.
You can find answers here "No module named simple" error in Django
from django.shortcuts import redirect
def my_view(request):
... does stuff
return redirect('/your_app/some_other_url/')
Situation in short. For some reason reverse() method does not work.
in PROJECT urls.py
url(r'^enrollment/', include('project.enrollment.urls')),
in APP urls.py
url(r'^thanks/$', 'enrollment.views.thanks', name='enroll_thanks'),
and in views.py
from django.core.urlresolvers import reverse
def thanks(request):
return render_to_response('enrollment/thanks.html', {}, context_instance=RequestContext(request))
def enroll(request):
''' some code for handling the form'''
return HttpResponseRedirect(reverse('enrollment.views.thanks'))
This reverse causes following error:
Could not import project.views. Error was: No module named views
in file ../django/core/urlresolvers.py in _get_callback, line 167
Any idea why this does not work? Next step is to call the thanks-view with a parameter, but that should be easy after this setup works. Should there be something more to be imported in views.py?
From the docs for reverse: "As part of working out which URL names map to which patterns, the reverse() function has to import all of your URLconf files and examine the name of each view. This involves importing each view function. If there are any errors whilst importing any of your view functions, it will cause reverse() to raise an error, even if that view function is not the one you are trying to reverse."
Are any of your urls referencing project.views....?
Not too sure of your module layout but based on your include() line in urls.py it looks like you may want to add "project." to the argument in your reverse() call as well.
reverse('project.enrollment.views.thanks')
That or you may have a bug in the view.
My app seeks to wrap the django.contrib.auth.views login and logout views with some basic auditing/logging capabilities. I'm following the prescription as described in the django-axes project, and in running on a server and some other tests, it works as expected, transparently without issue.
The code goes like this:
from django.contrib.auth import views as auth_views
from myapp.watchers import watch_login
class WatcherMiddleware(object):
def __init__(self):
auth_views.login = watch_login(auth_views.login)
And
def watch_login(func):
def decorated_login(request, *args, **kwargs):
#do some stuff
response = func(request, *args, **kwargs)
#more stuff
return response
return decorated_login
Urls:
#Edit: Added project's urls - just using vanilla django's auth login
(r'^accounts/login/$', 'django.contrib.auth.views.login',{"template_name":settings.LOGIN_TEMPLATE }),
However, in our build workflow, we run into some issues in the django.contrib.auth.tests.views.
Specifically, these are the tests that fail in django.contrib.auth:
ERROR: test_current_site_in_context_after_login (django.contrib.auth.tests.views.LoginTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\django\contrib\auth\tests\views.py", line 192, in test_current_site_in_context_after_login
response = self.client.get(reverse('django.contrib.auth.views.login'))
File "C:\Python26\lib\site-packages\django\core\urlresolvers.py", line 351, in reverse
*args, **kwargs)))
File "C:\Python26\lib\site-packages\django\core\urlresolvers.py", line 297, in reverse
"arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'myapp.watchers.decorated_login' with arguments '()' and keyword arguments '{}' not found.
======================================================================
ERROR: test_security_check (django.contrib.auth.tests.views.LoginTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\django\contrib\auth\tests\views.py", line 204, in test_security_check
login_url = reverse('django.contrib.auth.views.login')
File "C:\Python26\lib\site-packages\django\core\urlresolvers.py", line 351, in reverse
*args, **kwargs)))
File "C:\Python26\lib\site-packages\django\core\urlresolvers.py", line 297, in reverse
"arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'myapp.watchers.decorated_login' with arguments '()' and keyword arguments '{}' not found.
Only these two tests fail with the inclusion of the wrapped login monkey patch.
It seems like the reverse() call in the django auth test behaves differently than how an unpatched function does its thing.
The reason why we're going this route for wrapping logging vs. using django 1.3's new authentication signals is because the logging method provided there only tells you if a wrong attempts happens - it doesn't give you access to the request object to log additional information around that improper request. Patching the authentication form in that case would not have been helpful, hence our need to wrap the login function.
Am I doing something wrong with my wrap of the login function? Or is this as to be expected with tests failing due to other side effects, despite no change in overall functionality?
edit: I'm running python 2.6.4, django 1.2.5
Couldn't you simply wrap it in another view?
urls:
url(
r'^accounts/login/$',
'accounts.views.login',
{"template_name":settings.LOGIN_TEMPLATE }
),
accounts.views:
from django.contrib.auth import views as auth_views
def login(request, *args, **kwars):
# do some stuff
response = auth_views.login(request, *args, **kwars)
# more stuff
return response
Like this, django.contrib.auth.tests will be testing the view which they were written for and you can write your own tests for the "more stuff" you need.
I suspect this is the same underlying issue that affects django-registration in that the test runner only imports the URLs of the app being tested at the time -- ie, contrib.auth and not myapp There are various tickets about things similar to this issue but a quick scan of them implies the solution is to decouple things, which isn't going to be viable for your solution I'm guessing.
Another way around it would be to use Fabric file or Makefile to trigger a subset of tests, avoiding the two that fail because of your monkeypatch, and then add two alternate ape-friendly tests to replace them.
Django automatically creates an id field as primary key.
Now I need to get the object by this id.
object = Class.objects.filter()
How to write this filter?
If you want to get an object, using get() is more straightforward:
obj = Class.objects.get(pk=this_object_id)
I got here for the same problem, but for a different reason:
Class.objects.get(id=1)
This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as expected:
Class.objects.all()
Tail of the traceback for the get() method:
File "django/db/models/loading.py", line 197, in get_models
self._populate()
File "django/db/models/loading.py", line 72, in _populate
self.load_app(app_name, True)
File "django/db/models/loading.py", line 94, in load_app
app_module = import_module(app_name)
File "django/utils/importlib.py", line 35, in import_module
__import__(name)
ImportError: No module named myapp
Reading the code inside Django's loading.py, I came to the conclusion that my settings.py had a bad path to my app which contains my Class model definition. All I had to do was correct the path to the app and the get() method executed fine.
Here is my settings.py with the corrected path:
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
# ...
'mywebproject.myapp',
)
All the confusion was caused because I am using Django's ORM as a standalone, so the namespace had to reflect that.
You can also use get_object_or_404 django shortcut. It raises a 404 error if object is not found.
You can use:
objects_all=Class.objects.filter(filter_condition="")
This will return a query set even if it gets one object.
If you need exactly one object use:
obj=Class.objects.get(conditon="")
You can also do:
obj = ClassModel.get_by_id(object_id)
This works, but there may I'm not sure if it's supported in Django 2.
In case you don't have some id, e.g., mysite.com/something/9182301, you can use get_object_or_404 importing by from django.shortcuts import get_object_or_404.
Use example:
def myFunc(request, my_pk):
my_var = get_object_or_404(CLASS_NAME, pk=my_pk)