Django best practice – compare users

  • A+

I'm working on a small project and I have a user profile page.

This page has a variable called user. This variable contains the user object of the current profile page. The logged in user object is accessible with request.user

If you just print the user object it will return the username because the model returns this in the __str__ function

What is the best way to compare if the user profile belongs to the current user?

I could just write

if user == request.user 

But what if django changes the return value of the __str__ function?

or I could write

if user.username == request.user.username 


if == 

if user == request.user: is the correct way. Comparison is based on database primary keys, not on string representations. Django docs:


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: