gpt4 book ai didi

python - Django 身份验证模型错误 : name 'User' is not defined

转载 作者:太空狗 更新时间:2023-10-30 00:23:28 25 4
gpt4 key购买 nike

<强>1。错误代码:

NameError: 名称“用户”未定义

>>> 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

你有什么建议吗?

我能做什么?

有没有办法检查是否导入了用户授权模型?如果是,如果导入不正确怎么办?

我的书签应用有问题吗?

<强>2。我的模型.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

最佳答案

您在此处引用了 User:author = models.ForeignKey(User),但忘记在您的 models.py 中导入 User

将其放在 models.py 文件的顶部

from django.contrib.auth.models import User

编辑:

另一种(较新的)导入用户模型的方法 - 对于可配置的用户模型是:

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

返回的已配置用户模型将基于设置 AUTH_USER_MODEL

关于python - Django 身份验证模型错误 : name 'User' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25455379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com