Udders
Udders

Reputation: 6986

Redirecting a user in a django template

I have a django website that is spilt depending on what user type you are, I need to redirect users that are not entitled to see certain aspects of the site,

in my template, I have:

{% if user.get_profile.is_store %}
    <!--DO SOME LOGIC-->
{%endif%}

how would I go about redirecting said store back to the index of the site?

====EDIT====

def downloads(request):
    """
    Downloads page, a user facing page for the trade members to downloads POS etc
    """
    if not authenticated_user(request):
        return HttpResponseRedirect("/professional/")

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

    user = request.user
    account = user.get_profile()

    downloads_list = TradeDownloads.objects.filter(online=1)[:6]
    downloads_list[0].get_thumbnail()
    data = {}
    data['download_list'] = downloads_list

    return render_to_response('downloads.html', data, RequestContext(request))

I implement the answer from thornomad, and now I get his error

Environment:

Request Method: GET
Request URL: http://localhost:8000/professional/downloads
Django Version: 1.1.1
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
 'django.contrib.admin',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'sico.news',
 'sico.store_locator',
 'sico.css_switch',
 'sico.professional',
 'sico.contact',
 'sico.shop',
 'tinymce',
 'captcha']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware')


Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  92.                 response = callback(request, *callback_args, **callback_kwargs)
File "/var/www/sico/src/sico/../sico/professional/views.py" in downloads
  78.   if request.user.get_profile().is_store():
File "/var/www/sico/src/sico/../sico/shop/models.py" in is_store
  988.         return not self.account is None
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py" in __get__
  191.             rel_obj = self.related.model._base_manager.get(**params)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py" in get
  120.         return self.get_query_set().get(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in get
  305.                     % self.model._meta.object_name)

Exception Type: DoesNotExist at /professional/downloads
Exception Value: Account matching query does not exist.

Upvotes: 8

Views: 43912

Answers (7)

You can redirect with location, location.href,location.assign() and location.replace() in JavaScript in Django Templates as shown below. *location, location.href and location.assign() redirect to the URL adding the record to the history so we can go back to the previous page while location.replace() redirects to the URL not adding the record to the history so we cannot go back to the previous page:

<script>
{% if not request.user.is_authenticated %}
    location = "{% url '/professional/' %}";
{%endif%}
{% if request.user.get_profile.is_store %}
    location = "{% url '/' %}";
{%endif%}
</script>
<script>
{% if not request.user.is_authenticated %}
    location.href = "{% url '/professional/' %}";
{%endif%}
{% if request.user.get_profile.is_store %}
    location.href = "{% url '/' %}";
{%endif%}
</script>
<script>
{% if not request.user.is_authenticated %}
    location.assign("{% url '/professional/' %}");
{%endif%}
{% if request.user.get_profile.is_store %}
    location.assign("{% url '/' %}");
{%endif%}
</script>
<script>
{% if not request.user.is_authenticated %}
    location.replace("{% url '/professional/' %}");
{%endif%}
{% if request.user.get_profile.is_store %}
    location.replace("{% url '/' %}");
{%endif%}
</script>

Upvotes: 0

mizar
mizar

Reputation: 365

Of course sometimes we have views imported from django official code, or others that does not depend on us. We cannot place a redirect in those views, so the only way is through a template that these (untouchable) views are using.

Upvotes: 5

Roberto Rosario
Roberto Rosario

Reputation: 1858

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.

Upvotes: 17

vikingosegundo
vikingosegundo

Reputation: 52237

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 %}

Upvotes: 5

ariddell
ariddell

Reputation: 3423

I think you might want to do the redirect in the view code.

For example, this would work in Django 1.1.

from django.shortcuts import redirect

def my_view(request):
    if request.user.get_profile().is_store:
        return redirect('index')
    # normal view code here
    return ....

Documentation for redirect shortcut is here: http://docs.djangoproject.com/en/dev/topics/http/shortcuts/ The arguments to redirect() can be (quoting the docs):

  • A model: the model's get_absolute_url() function will be called.
  • A view name, possibly with arguments: urlresolvers.reverse() will be used to reverse-resolve the name.
  • A URL, which will be used as-is for the redirect location.

Upvotes: 2

Tom van Enckevort
Tom van Enckevort

Reputation: 4198

You wouldn't do this in the template, but in the view. Instead of calling render_to_response (which I presume you do now), you would call HttpResponseRedirect.

Upvotes: 1

thornomad
thornomad

Reputation: 6797

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.

Upvotes: 26

Related Questions