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?

1 Answer 1

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 %}
Sign up to request clarification or add additional context in comments.

4 Comments

How does that work with generic views? (I am using a ListView.) Adding a variable reversed to context?
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
@Asqiir Answers to this question explains how to do this with a class based view. stackoverflow.com/questions/15754122/…
@Asqiir. Yes, Haken Lid is right. Check out this link to see how to do it with CBV.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.