Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

request.path in django template

Tags:

django

I try something like this:

{% if request.path == 'contact' %}
    <p>You are in Contact</p>
{% endif %}

{% if request.path == 'shop' %}
    <p>You are in Shop</p>
{% endif %}

Why does not that work?

like image 948
Emanuel Avatar asked Mar 15 '13 15:03

Emanuel


People also ask

How can I get current URL in Django?

Run the following command to start the Django server. Execute the following URL from the browser to display the domain name of the current URL. The geturl1() function will be called for this URL that will send the domain name to the index. html file.

What does {{ NAME }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What is request in Django?

Django uses request and response objects to pass state through the system. When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function.

How a request is processed in Django?

Whenever a request comes into Django, it is handled by middlewares. When the Django server starts, the first thing it loads after settings.py is middlewares. The Request is processed by various middlewares one at a time. So, from the above list, when the request comes it will be passed through the security middleware.


2 Answers

By default Django's template processors are

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages"
)

( see documentation )

You need django.core.context_processors.request to use request in templates, so add it to that list in settings.py. If you don't have that variable there then set it.

like image 138
freakish Avatar answered Sep 23 '22 01:09

freakish


Try this:

{% if 'contact' in request.path %}
like image 33
okumu justine Avatar answered Sep 20 '22 01:09

okumu justine