2Answers
  • 12
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

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?

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 %}
  • 40
Reply Report
      • 2
    • Hmm. I see one inconsistency in my answer - try it with and username not in declined instead of and not username in declined. I doubt that would cause that template tag error, though. Does it work OK without the with?
      • 2
    • In what way does it fail? That expression is logically equivalent to an xor. If I had to guess, I'd check whether username is really the correct thing to be comparing against the ManyToMany field, but I can't be sure about that without seeing the models so I just copied what your non-working version had. My suspicion is that you probably want to be checking user in accepted, etc.
      • 1
    • Interesting, thanks for the tips about the with statement, however for some reason this conditional will not accept an else statement within it. keeps asking for {% endwith %}

Trending Tags