what exactly does request.user return in django, can we compare it with a string?

Viewed 620

I am new to Django and trying out somethings. I am thinking to return a page named "in_accessable.html" if a normal user access the "\create" page (which calls the function named medicine_create_view"), else medicine_create.html.

The name of admin is "npend"(checked usingprint(request.user)) so I gave a if statement to check if the user name is 'npend' or not, I used request.user method to get the user name, even if I access the page with admin I am getting a false in if statment I tried printing request.user == "npend", which prints False every time.

Can anyone help me rectifing this problem, Thank You.

Code Used:

def medicine_create_view(request, *args,**kwargs):
    my_form = Raw_Medicine_Form()
    if request.method == 'POST':
        my_form = Raw_Medicine_Form(request.POST)
        if my_form.is_valid():
            print(my_form.cleaned_data)
            Medicine.objects.create(**my_form.cleaned_data)
        else:
            print(my_form.errors)
    my_form = Raw_Medicine_Form()
    context ={
        "form" : my_form,
    }
    #print(request.user)
    #print(request.user=="npend") 
    if(request.user=="npend"): return render(request,"App_1/medicine_create.html",context)
    else: return render(request,"error_files/not_acessable.html",{})

The Out_Put screen is as shown:

False
npend
[17/Jun/2021 09:37:36] "GET /create/ HTTP/1.1" 200 227
2 Answers

request.user is a User object. That is why you get a False value when comparing. But while printing the User object the __str__ magic method is called and the username is printed as string.

print(request.user) # string
print(request.user=="npend") # False

What you can do is compare it with actual username value:

if(request.user.username=="npend"): 
  return render(request,"App_1/medicine_create.html",context)

request.user is a User object. If you print it, it prints the username, but to fetch the value of the username, you must use request.user.username.

The documentation would have told you this. I just Googled it.

Related