0

The url: myurl/?page=1&reverse

Now I want to check in the template whether reverse is in there:

{% if request.GET.reverse %}
  do somthing
{% endif %}

But what's in between of if and endif never happens!

What should I use instead of request.GET.reverse?

Asqiir
  • 607
  • 1
  • 8
  • 23

1 Answers1

1

Why not put that logic inside your view? Like this:

# Function Based View (FBV)

def my_view(request):
    reversed = request.GET.get('reverse', '')
    return render(request, 'template.html', locals())

# Class Based View (CBV)
class MyView(ListView):
    template_name = 'path/to/template.html'
    queryset = MyModel.objects.filter(...)
    context_object_name = 'my_obj'

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['reversed'] = self.request.GET.get('reverse', '')
        return context

Then do:

{% if reversed %}
    do somthing
{% endif %}

On the other hand, if you still want to do this kind of logic in your template then you should create your own filter like this:

from django import template

register = template.Library()    

def is_in_dict(d, key):
    return key in d

and use it like this:

{% load my_filters %}

{% if request.GET|is_in_dict:"reverse" %}
    do somthing
{% endif %}
nik_m
  • 11,825
  • 4
  • 43
  • 57
  • 1
    How does that work with generic views? (I am using a ListView.) Adding a variable `reversed` to context? – Asqiir Apr 22 '17 at 15:13
  • The value of `reversed` in this case would be falsey, since it's an empty string, even if the key exists. It would be better to use something like this: `reversed = 'reverse' in request.GET` – Håken Lid Apr 22 '17 at 15:14
  • @Asqiir Answers to this question explains how to do this with a class based view. http://stackoverflow.com/questions/15754122/url-parameters-and-logic-in-django-class-based-views-templateview – Håken Lid Apr 22 '17 at 15:17
  • @Asqiir. Yes, Haken Lid is right. Check out this link to see how to do it with CBV. – nik_m Apr 22 '17 at 15:18