0

I'm working on Django template and setting Conditional branching whether there is a "query" or not.

  {% if {{ request.GET.query }} == "" %}
  <td><a href="/detail/{{item.id}}/{{item.item_hs6}}">detail</a></td>
  {% else %}
  <td><a href="/detail/{{item.id}}/{{item.item_hs6}}/{{ request.GET.query }}">detail</a></td>
  {% endif %}

When I execute the above code, the error occurs here.

Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '{{' from '{{'

I know the code below is something wrong

{% if {{ request.GET.query }} == "" %}

How should I judge whether there is a query or not in Template?

I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you

daylyroppo3
  • 79
  • 1
  • 9
  • Does this answer your question? [Django -- Template tag in {% if %} block](https://stackoverflow.com/questions/11372177/django-template-tag-in-if-block) – Abdul Aziz Barkat Jun 25 '21 at 09:13
  • Hello @daylyroppo3 you don't have to use `{{}}` inside `{% if %}` just use like this `{% if request.GET.query == "" %}` – Ankit Tiwari Jun 25 '21 at 09:16
  • and best way to judge that query is there or not just do like this `{% if not request.GET.query %}` it will return `False` if it is `None` or if it is `""` – Ankit Tiwari Jun 25 '21 at 09:19

1 Answers1

0

Django template variables and tags

Within the Django template tag you can access variables directly. There is no need for another Jinja tag to declare the variable.

{% if {{ request.GET.query }} == "" %}

should be

{% if request.GET.query == "" %}

Usage of request parameters

If I understand your template correctly you're reflecting information from a request directly on your page. This should be considered a security issue!

The template in the model, template, view of Django should only handle how information is displayed and what information is displayed. It should not create it's own information, which is what you're doing.

You should let whoever creates the view handle the request. Just make sure you get the necessary context for your template so you can achieve your design goals.

//EDIT

Check for existence and use it

Use this with caution! I do not recommend doing this in the template it's just to showcase the access.

  {% if "query" in request.GET %}
  <td><a href="/detail/{{item.id}}/{{item.item_hs6}}/{{ request.GET.get('query') }}">detail</a></td>
  {% else %}
  <td><a href="/detail/{{item.id}}/{{item.item_hs6}}">detail</a></td>
  {% endif %}
SvenTUM
  • 784
  • 1
  • 6
  • 16
  • @daylyroppo3 one more addition: if you want to check if your parameter _query_ is in the requests GET parameters you should use `if x in y` as it's a **QueryDict**. I'll update this in the post. – SvenTUM Jun 25 '21 at 10:02