1

I have a condition like this:

{% if object.author == user or object.res_person_1_username == user %}

If I view variables with, for example:

<p class="article-content mb-1"><strong>object.res_person_1_username: </strong>{{ object.res_person_1_username }}</p>

They are the same, all three, but condition

object.res_person_1_username == user

is always False. Why is that? What I'm missing? Do I need to change data type or something?

models.py

res_person_1_username = models.TextField(blank=True, max_length=40)
4
  • You are comparing a username with a User object. Commented Jun 7, 2021 at 20:19
  • Are they both strings? or us one a user class and the other a text field? Commented Jun 7, 2021 at 20:19
  • @ChrisDoyle: user is normally passed automatically to the template as request.user (that is why request is passed in the render(...) call, so this is a comparison between a User object and a string. Commented Jun 7, 2021 at 20:22
  • To make things simple, just change res_person_1_username in ur model.py to a Foreignkey and link it to auth User model Commented Jun 7, 2021 at 20:38

1 Answer 1

1

You are comparing a username with a User object. A string 'foo' is not the same as a User with 'foo' as username.

You can check this with:

{% if object.author == user or object.res_person_1_username == user.username %}

But that being said, to refer to a model object, one normally uses a ForeignKey [Django-doc]. This guarantees referential integrity, makes filtering, querying, etc. more convenient, and will also create an index automatically for that column.

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

1 Comment

It worked flawlessly, thank you for your help

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.