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.
The
userfield is aForeignKey. That means it must reference some user.By definition, the
AnonymousUseris no user: in Django, there is noAnonymousUserAandAnonymousUserB. They’re all the same:AnonymousUser.Conclusion: you can’t put an
AnonymousUserin aUserForeignKey.The solution to your issue is pretty straightforward though: when the
Useris anonymous, just leave the field blank. To do that, you’ll need to allow it: