[Fixed]-Check for request.GET variable in the template

57👍

Variables are case-sensitive – so, assuming as lazerscience points out that you actually have the request object in the context, you would need to use {% if request.GET.my_var %}.

13👍

Check if you have django.core.context_processors.request in your TEMPLATE_CONTEXT_PROCESSORS in settings.py.

If not put it there, or add request yourself to your rendered context.

http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request

0👍

Passthrough your request.GET parameters to your Django template:
example – we have a page register/ with certain parameters in the form, and have a duplicate page registerprint/ without pagination, as a full list of filtered records, and we need to redirect user from register/ to registerprint/ by passing through some of the parameters from the register/ page

 urls.py
from django.urls import path
from .views import record_list, record_list_print
urlpatterns = [
    path('register/', view=record_list, name='register'),
    path('registerprint/', view=record_list_print, name='registerprint'),
  ]

views.py
def strx(string):
    param=str(string)
    if param=='None':
        return ''
    else:
        return param
def record_list(request):
      req = {'type': strx(request.GET.get('type')),
        'profile' : strx(request.GET.get('profile')),
        'org_nazvanie':strx(request.GET.get('org_nazvanie')),
        'org_filial':strx(request.GET.get('org_filial')),
        'org_tema':strx(request.GET.get('org_tema')),
        'org_address':strx(request.GET.get('org_address')),
        'info_naimenovanie':strx(request.GET.get('info_naimenovanie')),
        'info_forma':strx(request.GET.get('info_forma')),
        'info_dostup':strx(request.GET.get('info_dostup')),
        'all_in_one':strx(request.GET.get('all_in_one'))
    }
    return render(request, 'bot/registerfilterpag.html', { 'req' : req})

and the registerfilterpag.html. In this template we create a button that redirects user to the duplicate copy of the page, with some of the URL parameters we’ve extracted in views.py from the initial request. The button itself is not printable, so, the ‘noprint’ style is added to the markup.

 registerfilterpag.html
 {% extends 'bot/base.html' %}
 {% block Body %}
<style>
@media print {
  .noprint {
    display: none !important;
  }
}
  </style>
    <a class="btn btn-info noprint" role="button" href="../../registerprint/?type={{ req.type }}&profile={{ req.profile }}&org_nazvanie={{ req.org_nazvanie }}&org_filial={{ req.org_filial }}&org_tema={{ req.org_tema }}&org_address={{ req.org_address }}&info_naimenovanie={{ req.info_naimenovanie }}&info_forma={{ req.info_forma }}&info_dostup={{ req.info_dostup }}&all_in_one={{ req.all_in_one }}&submit=%D0%9F%D0%BE%D0%B8%D1%81%D0%BA">version for printing</a>
 {% endblock %}

Leave a comment