[Fixed]-Django save model with anonymous user

18👍

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

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

Conclusion: you can’t put an AnonymousUser in a 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)

0👍

You might approach it like this where,

user = None
if request.user.is_authenticated:
    user = request.user

project = Project.objects.create(
              user=user,
              product=product_instance,
              ...
          )

And following this use the "user" in your methods. When it is anonymous user, it will be none.

Dont forget to define the user in your Project model as

user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, ...

Leave a comment