3

here is my Django code

print request.user.role
print request.user.role is "Super"
print request.user.role == "Super"
print "Super" is "Super"

and the output on console is

Super
False
False
False
True

I am wondering why it is not matching the exact string

8
  • 2
    Try type(request.user.role) Commented Mar 11, 2015 at 16:21
  • <class 'django.contrib.auth.models.Group'> Commented Mar 11, 2015 at 16:23
  • 1
    print prints whatever str returns, so you might compare str(request.user.role) == "Super", but there's probably a better way. Commented Mar 11, 2015 at 16:24
  • 3
    And, never, ever use is to compare two values. Commented Mar 11, 2015 at 16:25
  • 2
    It does not look like a good idea to check roles by converting user.role to string and comparing with role name - it's error prone, potentially uses more memory and has plenty other things bad with it. There should be an enum with all the values and comparison should look like user.role == roles.super or user.role.is_super etc. Commented Mar 11, 2015 at 16:31

2 Answers 2

4

It is because request.user.role is not a string. As a result, comparing it with a string "Super" will return false, as there is no implicit type comparison. You must convert it to a string if you want to compare it to one. To convert to a string, you can try this:

str(request.user.role)

Your last print returns true because you are just comparing the string "Super" to itself, evidently. Also as a side note, you only want to use is when comparing identities, not values.

Sign up to request clarification or add additional context in comments.

Comments

3

Please do not use string comparison to check for user roles. This approach is error prone, may use more memory for new created strings and is dangerous overall. For example if value that represents role is not it's name you will have to keep track of name-value mapping yourself. Or if library will change it's mind and swap names to integers etc.

All libraries that provide such functionality has roles enum lying somewhere with all the values for roles. So, for example, in django-user-roles you can do

user.role.is_super # maybe role.is_Super
# or
from userroles import roles
user.role == roles.super # maybe roles.Super

This is much more readable and safer aproach.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.