Search code examples
pythondjangodjango-rest-frameworkdjango-templatesdjango-tagging

TemplateSyntaxError at GET in Django template


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


Solution

  • 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 %}