Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django save model with anonymous user

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.

like image 368
Darwin Tech Avatar asked Dec 20 '12 01:12

Darwin Tech


1 Answers

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)
like image 161
Thomas Orozco Avatar answered Oct 17 '22 16:10

Thomas Orozco