[Fixed]-Using querydict item for if-statement

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

Leave a comment