Opened 6 years ago

Closed 6 years ago

#29782 closed Cleanup/optimization (fixed)

Better error message when filtering users with AnonymousUser

Reported by: Sveder Owned by: Ramon Saraiva
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When trying to filter a model with User ForeignKey on AnonymousUser, we get a cryptic:
Exception Value: int() argument must be a string or a number, not 'AnonymousUser'

For example:
https://stackoverflow.com/questions/3439709/how-to-cater-for-anonymoususer-when-filtering-based-on-user

I think this deserves a better error message, for example something like:
ValueError("Can't filter User field with AnonymousUser").

Change History (8)

comment:1 by Ramon Saraiva, 6 years ago

Owner: changed from nobody to Ramon Saraiva
Status: newassigned

comment:2 by Carlton Gibson, 6 years ago

Triage Stage: UnreviewedAccepted
Type: UncategorizedCleanup/optimization
Version: 2.1master

Yep. Great. Better error messages FTW! 🙂

comment:3 by Ramon Saraiva, 6 years ago

Still trying to understand what piece of code would be responsible for this behaviour.
I wonder if overwriting AnonymousUser's __int__ would be too naive?

Since AnonymousUser is not inheriting from Model, it happens that its instance is passed all the way over to the field get_prep_value and then int(value -> AnonymousUser) is called.
Any guidance/idea about what should be responsible for doing this validation?

comment:4 by Tim Graham, 6 years ago

Easy pickings: unset

An obvious implementation doesn't come to mind. I'm not sure if it's feasible.

comment:5 by Adam Johnson, 6 years ago

{{AnonymousUser.int}} might work, if you make the error message more generic like {{TypeError("Cannot cast AnonymousUser to int. Are you trying to use it in place of User?")}}

Version 0, edited 6 years ago by Adam Johnson (next)

comment:6 by Ramon Saraiva, 6 years ago

Ok, I'll work on that patch and we can continue from there.

comment:7 by Tim Graham, 6 years ago

Has patch: set

comment:8 by Tim Graham <timograham@…>, 6 years ago

Resolution: fixed
Status: assignedclosed

In 2349cbd9:

Fixed #29782 -- Added better error message when filtering queryset with AnonymousUser.

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