Django model error: user name not defined

1. Error codes:

NameError: user name is not defined

>>> myproject ME$ python manage.py shell NameError: name 'User' is not defined myproject ME$ python manage.py shell Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.contrib.auth.models import User >>> user = User.objects.create_user('john', ' lennon@thebeatles.com ', 'johnpassword') >>> user.is_staff = True >>> user.save() >>> User.objects.all() [<User: superuser>, <User: john>] >>> from django.db import models >>> from django.contrib.auth.models import User >>> >>> >>> from django.conf import settings >>> user = models.ForeignKey(settings.AUTH_USER_MODEL) >>> User.objects.all() [<User: superuser>, <User: john>] >>> user.save() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'ForeignKey' object has no attribute 'save' >>> from django.conf import settings 

Do you have any suggestions?

What can I do?

Is there any way to check if a custom model has been imported? If so, what can I do if it was not imported correctly?

Is there a problem with my bookmarks?

2. My models.py:

 from django.db import models class Bookmark(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=200, blank=True, default="") url = models.URLField() timestamp = models.DateTimeField(auto_now_add=True) def __unicode__(self): return "%s by %s" % (self.url, self.author.username) class Tag(models.Model): bookmarks = models.ManyToManyField(Bookmark) slug = models.CharField(max_length=50, unique=True) def __unicode__(self): return self.slug 
+5
source share
1 answer

You refer to User here: author = models.ForeignKey(User) , but you forgot to import User into your models.py

Put this at the top of your models.py file

 from django.contrib.auth.models import User 

EDIT:

An alternative (newer) way to import a user model is for custom user models:

 from django.contrib.auth import get_user_model User = get_user_model() 

The returned configuration of the user model will be based on the setting AUTH_USER_MODEL

+13
source

Source: https://habr.com/ru/post/1200952/


All Articles