You can't use AnonymousUser in the database API
|Reported by:||Mason Simon <masonsimon+django@…>||Owned by:||adrian|
|Component:||Database layer (models, ORM)||Version:||master|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
My situation is this: I have a model with a OneToOne field to the User model to support the extended features that I need my users to have. In one of my views I used code like the following to branch based on whether the user is logged in:
try: app_user = AppUser.objects.get(user=request.user) # show personal view for this user: ... except AppUser.DoesNotExist: # user isn't logged in; show some other view: ...
I think that this code worked for me with the MySQL backend, but when I changed over to sqlite3 it gave me InterfaceError. But, I vaguely remember updating my checked-out copy of django SVN at that time, so perhaps there was a change to the codebase that caused my results. Either way, I've done some preliminary tracing and found that the sqlite3 backend code is sending SQL that looks like this:
SELECT columns FROM the_table WHERE ("app_user"."user_id" = ?) with <class 'django.contrib.auth.models.AnonymousUser'> as a parameter.
When an actual User is given instead of AnonymousUser, the parameter is that user's numerical id. I haven't dug deep enough into django's code to determine how AnonymousUser should be handled in this case to produce a DoesNotExist error (assuming that's the desired behavior), but ticket #2144 looks related.
As an aside: I've changed my code to branch on request.user.is_authenticated(), and that works fine.
Change History (2)
comment:1 Changed 9 years ago by Michael Radziej <mir@…>
- Keywords sqlite3 removed
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Summary changed from attempt to retrieve non-existent object by foreign key to AnonymousUser raises InterfaceError instead of DoesNotExist to You can't use AnonymousUser in the database API