Search code examples
djangoclassdjango-templatesblock

Django, trying to change the class attribute of an extended nav bar


I created a "base.html" template to hold my nav bar and other elements that are recurrent on my website. When I extend this template and put values into my blocks one of them doesn't want to work properly.

In my code I try to set the class value of my nav element to "active" depending on which page I'm in (it might not be the best solution). This block never works.

Thank you for your help :)

urls.py

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^addProduct/$', views.addProduct, name='addProduct'),
]

views.py

def index(request):
    latest_product_list = Product.objects.all().order_by('-id')[:5]
    return render(request, 'main/index.html', {'latest_product_list': latest_product_list})

def addProduct(request):
    # Do things
    return render(request, 'main/add_product.html', {'form':form})

base.html

<!DOCTYPE html>
<html lang="fr">
<head>
#header informations
</head>

<body>
    <div class="container-fluid">

        <div class="row">
            {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
        </div>

        <ul class="nav nav-pills" role="tablist">
            <li role="presentation" class="{% block navbar_class-index %}{% endblock %}"><a href="{% url 'main:index' %}">Index</span></a></li>
            <li role="presentation" class="{% block navbar_class-addProduct %}{% endblock %}"><a href="{% url 'main:addProduct' %}">Ajouter un produit</a></li>
        </ul>

        <div class="row" id="content">
            {% block content %}{% endblock content %}
        </div>
    </div>

</body>

index.html

{% extends "base.html" %}

{% block navbar_class-index %}active{% endblock %}

{% block content %}

<div class="col-md-12">
   ## Here is my content
</div>
{% endblock content %}

add_product.html

{% extends "base.html" %}

{% block navbar_class-addProduct %}active{% endblock %}

{% block content %}
<div class="col-md-12">
    <form action="{% url 'main:addProduct' %}" method="post">
    {% csrf_token %}
    <label> Entrez votre produit et cliquez sur Add Product.</label><br/><br/>
    <label> Produit : </label>{{form.form_product_url}}
    <input type="submit" value="Add Product" />
    </form>
</div>
{% endblock content %}

Solution

  • I guess your base.html file is not in the correct folder !