Django: model not defined? - django

I can't use the model I defined in Django.
My model is defined inside my_object/models.py:
class MyObject(models.Model):
name = models.CharField("Name")
If I launch shell_plus, I can't use my model:
# ./manage.py shell_plus
# Shell Plus Model Imports
...
from my_object.models import MyObject
...
In [1]: MyObject
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-05203d19fbcd> in <module>
----> 1 MyObject
NameError: name 'MyObject' is not defined
My config: Python 3.6, Django 1.11.
EDIT: I don't have the following problem anymore, it was caused by a legitimate fail, the query does not have any results:
And I cannot launch tests either, I get this error:
my_object.models.DoesNotExist: MyObject matching query does not
exist.

I believe I found the origin of this behaviour, and ipdb seems to be the culprit.
Removing the import ipdb line inside one of my Python files solved my problem, I don't really know why.

Related

Can I use fixtures to create a test from production database?

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.

Django NameError: name 'models' is not defined

I have a small application that I wrote in python. Did some research on some web frameworks and decided to use django. I'm reading through the manual and going step by step to learn as much, however I'm stuck on the example given on page 19. When I type the command an I get and error.
import datetime
from django.utils import timezone
# ...
class Poll(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
Error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'models' is not defined
I googled "Django NameError:" and didn't find much.
Thanks.
You accidentally missed the whole import for models.
from django.db import models
Another instance of this error appears when you miss spell stuff :)
like Models.Model instead of models.Model. Quite annoying.
Got this error when accidentally using models.CharField in a form, instead of using forms.CharField

ImportError: No module named models

I am going a tad crazy here. I keep getting this error: ImportError: No module named models and I am not sure why. Here is what I have found so far...
>>> from django.shortcuts import get_object_or_404, redirect
>>> from mystore.cart import cart
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/Jeff/django/mystore/cart/cart.py", line 3, in <module>
from mystore.cart.models import CartItem
ImportError: No module named models
>>>
I am not sure what's going on with this... line 3 in cart.py is this:
from mystore.cart.models import CartItem
If I try to do: from mystore.cart.models import CartItem it works fine...
Any suggestions?
Almost certainly, you have a circular dependency: mystore.cart.cart is importing mystore.cart.models, which in turn is trying to import mystore.cart.cart.
You should determine if both of those imports are necessary, and if either of them could be moved out of the global scope into a function or method.
Why are you doing from mystore.cart import cart? That should be just from mystore import cart.
Very early in the mystore.cart.models an error is occurring that's why nothing in models.py can be imported. The error can be a circular import, a conditional statement that's triggered during runtime but not at the command prompt or is happening inside something else your are importing at the beginning of models.py
You have to put a point before.
bad
from models import *
good
from .models import *
that means that is at the same level.

Django path error - No module named models

I have an import error in a Django app, I guess it's pretty simple but I can't figure it out…
It's a simple notepad app, called «notes» with 2 models, «note» & «category». To clean things up, I wanted to seperate each models views & urls, so here is what I get:
/notes
admin.py
forms.py
models.py
/urls
category.py
note.py
/views
category.py
note.py
The problem is that my views don't find the models, here is the Traceback - http://dpaste.com/hold/539425/ and parts of the code: http://dpaste.com/hold/539416/
I didn't mention the _init_.py files in the above snippet, but I double-checked all of them…
Your code pastie says from notes.models import Category, Note but your traceback says from models import Category, Note. It's hard to tell if those are the same line because you're only pasting snippets. Still, it should be 'from notes.models import foo' always.
Are you sure you're always referencing the notes app in your models import?
UPDATE:
If you're using the correct from foo.models import bar syntax, then my next thoughts are that you've possibly got a circular dependency that's stopping Python importing things from the models file.
But the traceback implies the notes/models.py can't be found. So... when you say you double-checked the init.py files, that doesn't mean they're right. :p There should be one in notes/ and also in notes/urls/ -- they don't have to contain anything.
It should be
from notes.models import Category, Note

PyLint failing for a number of Django imports

I am using PyLint,
pylint -e app/views.py
Gives me errors like
E: 3: No name 'shortcuts' in module 'django'
E: 7: No name 'db' in module 'django'
But passes for other django imports. Since it passes for other Django import Django is on my pythonpath.
I think I figured it out -- if you jump into a python session and actually try to import anything from django.db
from django.db import *
you'll get an error about DJANGO_SETTINGS_MODULE not being set. Setting the environment variable and pointing it to your settings.py like app.settings should fix the error for you.
When I tried this in an Eclipse/PyDev config I had to disable pylint, build, then re-enable pylint to finally clear out those errors.
Have you tried djangolint, which is a wrapper around Pylint with Django-specific settings?