Redirecting a user in a django template

You will want to do this, I think, in a view not in the template. So, something like:

from django.http import HttpResponseRedirect

def myview(request):
    if request.user.get_profile().is_store():
        return HttpResponseRedirect("/path/")

    # return regular view otherwise

You could also use a @decorator for the view if you found yourself needing to do this a lot.


Use the HTML's raw redirection.

{% if user.get_profile.is_store %}
    <meta http-equiv="REFRESH" content="0;url=http://redirect-url">
{% endif %}

or provide the redirection url as a context variable

{% if user.get_profile.is_store %}
    <meta http-equiv="REFRESH" content="0;url={{ user.get_profile.store_url }}">
{% endif %}

if memory serves right, this has to be inside the "head" tag, but modern browser are more forgiving, Firefox 4 allowed it inside the "body" tag and worked ok.


You really don't want to redirect in a template, as said in all other answers.

But if redirecting in a view is no option (why ever), you can do this:

{% if user.get_profile.is_store %}
    {% include '/path/to/template' %}
{% else %}
    {% include '/path/to/another_template' %}
{% endif %}

Tags:

Python

Django