Opened 16 years ago

Closed 16 years ago

#3413 closed (invalid)

You can't use AnonymousUser in the database API

Reported by: Mason Simon <masonsimon+django@…> Owned by: Adrian Holovaty
Component: Database layer (models, ORM) Version: dev
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: 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:

  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 16 years ago by Michael Radziej <mir@…>

Keywords: sqlite3 removed
Summary: attempt to retrieve non-existent object by foreign key to AnonymousUser raises InterfaceError instead of DoesNotExistYou can't use AnonymousUser in the database API

The class AnonymousUser is not a model class, and it is not intended to be used in a query. You have to check is_authenticated or something equivalent, as you correctly found out. This is not related to sqlite, and I'd expect MySQL to fail, too (if not, it might be a bug ;-)

What made you think that you could use request.user in such a way? Perhaps this needs a clarification in the docs.

comment:2 Changed 16 years ago by Michael Radziej <mir@…>

Resolution: invalid
Status: newclosed

I'm closing this since the reporter does not reply to questions.

Note: See TracTickets for help on using tickets.
Back to Top