15

I have a Django model:

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

In my 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:

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?

Any assistance much appreciated.

Darwin Tech
  • 18,449
  • 38
  • 112
  • 187

2 Answers2

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)
Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
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, ...
london_utku
  • 1,070
  • 2
  • 16
  • 36