Django使用匿名用户保存模型

时间:2021-04-16 00:25:19

I have a Django model:

我有一个Django模型:

class Project(models.Model):
    user = models.ForeignKey(User)
    zipcode = models.CharField(max_length=5)
    module = models.ForeignKey(Module)

In my views.py:

在我的views.py中:

def my_view(request):  
    ...
    project = Project.objects.create(
                  user=request.user,
                  product=product_instance,
                  ...
              )
    project.save()

I want to be able to save user as an authenticated user OR an AnonymousUser (which I can update later). However, if I'm not logged in I get this error:

我希望能够将用户保存为经过身份验证的用户或AnonymousUser(我稍后可以更新)。但是,如果我没有登录,我会收到此错误:

ValueError: Cannot assign "<django.utils.functional.SimpleLazyObject object at 0x1b498d0>": "Project.user" must be a "User" instance.

I guess that Django won't save the AnonymousUser because it is not a User as defined in the User model. Do I need to add the anonymous user to the User model, or am I missing something?

我猜Django不会保存AnonymousUser,因为它不是User模型中定义的User。我是否需要将匿名用户添加到用户模型,或者我错过了什么?

Any assistance much appreciated.

任何协助非常感谢。

1 个解决方案

#1


10  

The user field is a ForeignKey. That means it must reference some user.

用户字段是ForeignKey。这意味着它必须引用一些用户。

By definition, the AnonymousUser is no user: in Django, there is no AnonymousUserA and AnonymousUserB. They're all the same: AnonymousUser.

根据定义,AnonymousUser不是用户:在Django中,没有AnonymousUserA和AnonymousUserB。它们都是一样的:AnonymousUser。

Conclusion: you can't put an AnonymousUser in a User ForeignKey.

结论:您不能将AnonymousUser放在User ForeignKey中。


The solution to your issue is pretty straightforward though: when the User is anonymous, just leave the field blank. To do that, you'll need to allow it:

您的问题的解决方案非常简单:当用户匿名时,只需将该字段留空即可。要做到这一点,你需要允许它:

user = models.ForeignKey(User, blank = True, null = True)

#1


10  

The user field is a ForeignKey. That means it must reference some user.

用户字段是ForeignKey。这意味着它必须引用一些用户。

By definition, the AnonymousUser is no user: in Django, there is no AnonymousUserA and AnonymousUserB. They're all the same: AnonymousUser.

根据定义,AnonymousUser不是用户:在Django中,没有AnonymousUserA和AnonymousUserB。它们都是一样的:AnonymousUser。

Conclusion: you can't put an AnonymousUser in a User ForeignKey.

结论:您不能将AnonymousUser放在User ForeignKey中。


The solution to your issue is pretty straightforward though: when the User is anonymous, just leave the field blank. To do that, you'll need to allow it:

您的问题的解决方案非常简单:当用户匿名时,只需将该字段留空即可。要做到这一点,你需要允许它:

user = models.ForeignKey(User, blank = True, null = True)