Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django template if or statement

Basically to make this quick and simple, I'm looking to run an XOR conditional in django template. Before you ask why don't I just do it in the code, this isn't an option.

Basically I need to check if a user is in one of two many-to-many objects.

req.accepted.all 

and

req.declined.all

Now they can only be in one or the other (hence the XOR conditional). From the looking around on the docs the only thing I can figure out is the following

{% if user.username in req.accepted.all or req.declined.all %}

The problem I'm having here is that if user.username does indeed appear in req.accepted.all then it escapes the conditional but if it's in req.declined.all then it will follow the conditional clause.

Am I missing something here?

like image 367
Llanilek Avatar asked Oct 09 '13 23:10

Llanilek


People also ask

How do you do if statements in Django?

How to use if statement in Django template. In a Django template, you have to close the if template tag. You can write the condition in an if template tag. Inside the block, you can write the statements or the HTML code that you want to render if the condition returns a True value.

What {{ NAME }} means in a Django template?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What is DTL in Django?

Django Template Language (DTL) is the primary way to generate output from a Django application. You can include DTL tags inside any HTML webpage. The basic DTL tag you can include in an HTML webpage is: 1. {% Tag %}


2 Answers

and has higher precedence than or, so you can just write the decomposed version:

{% if user.username in req.accepted.all and user.username not in req.declined.all or
      user.username not in req.accepted.all and user.username in req.declined.all %}

For efficiency, using with to skip reevaluating the querysets:

{% with accepted=req.accepted.all declined=req.declined.all username=user.username %}
    {% if username in accepted and username not in declined or
          username not in accepted and username in declined %}
    ...
{% endif %}
{% endwith %}
like image 152
Peter DeGlopper Avatar answered Oct 12 '22 14:10

Peter DeGlopper


Rephrased answer from the accepted one:

To get:

{% if A xor B %}

Do:

{% if A and not B or B and not A %}

It works!

like image 27
db0 Avatar answered Oct 12 '22 12:10

db0