#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: master
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 Changed 15 months ago by Ramon Saraiva

Owner: changed from nobody to Ramon Saraiva
Status: newassigned

comment:2 Changed 15 months ago by Carlton Gibson

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

Yep. Great. Better error messages FTW! 🙂

comment:3 Changed 15 months ago by Ramon Saraiva

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 Changed 15 months ago by Tim Graham

Easy pickings: unset

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

comment:5 Changed 15 months ago by Adam (Chainz) Johnson

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?")

Last edited 15 months ago by Adam (Chainz) Johnson (previous) (diff)

comment:6 Changed 15 months ago by Ramon Saraiva

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

comment:7 Changed 15 months ago by Tim Graham

Has patch: set

comment:8 Changed 15 months ago by Tim Graham <timograham@…>

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