how to give {% url '' %} to a variable? - django

I have this requirement in django template:
{% if user.is_admin %}
<a href='{% url 'url_to_admin' %}'>admin url</a>
{% else %}
<a href='{% url 'url_to_other %}'>other url </a>
{% endif %}
and now, I want let it more simple, I want let url to a variable `xx', like this:
if user.is_admin:
myurl = {% url 'url_to_admin' %}
else:
myurl = {% url 'url_to_other' %}
<a href={{myurl}} > url </a>
But I don't know how to write in django's template?

The url tag can be assigned to a variable through using as.
{% url 'my_url' as foobar %}
{{ foobar }}
But that doesn't make sense in the current place where you're using it. Just assign the anchor tags inside of the if/else statements
{% if user.is_admin %}
admin
{% else %}
other
{% endif %}

Not the answer, but you may try this:
<a href='{% if user.is_admin %}{% url 'url_to_admin' %}{% else %}{% url 'url_to_other' %}'>other url </a>

why don't you handle it in the views before you render the template, try something like in your view.py
if User.is_admin:
url = 'url_to_admin'
else:
url = 'url_to_other'
render(request, "your_template.html", {'url' : url})
then you can go ahead and call your url in your template like
<a href= "{{ url }}>url</a>"

views.py
from django.core.urlresolvers import reverse
def my_view(request):
if request.user.is_admin:
my_url = reverse('my_admin_view')
else:
my_url = reverse('my_other_view')
return render(request, 'my_template.html', {'my_url': my_url })
Using django.core.urlresolvers.reverse
my_template.html
This is a link

Related

Django Template doesn't work with a for loop in range. Why?

VIEWS.PY
def index(request):
posts = Post.objects.all()
posts_quantity = range(1)
return render(request, 'index.html', {'posts':posts, 'posts_quantity':posts_quantity})
HTML
{% for index in posts_quantity %}
<a href = "{% url 'architectural_post' posts.index.slug %}" class = "post">
{% endfor %}
it gives me an error: Reverse for 'architectural_post' with arguments '('',)' not found.
But everything works well if I put 0 instead of index, like this (just for debugging):
{% for index in posts_quantity %}
<a href = "{% url 'architectural_post' posts.0.slug %}" class = "post">
{% endfor %}
Why and how to fix it?
Thanks.
Django is not interpreting posts.index.slug as posts.0.slug. Instead, Django is trying to find an attribute called index on the posts object.
It's not very intuitive, but that's how it is.
You can fix it by iterating over the posts directly:
{% for post in posts %}
<a href="{% url 'architectural_post' post.slug %}" class="post">
{% endfor %}

TemplateDoesNotExist at /inventory/render_results/ error message in django

I am using code that I've used before but it is throwing an error, 'TemplateDoesNotExist at /inventory/render_results/' and I cannot find the typo or logic miss. The template does exist and when I review the code, the query is performing correctly. I'm at a loss.
search_device_list.html
{% extends "inventory/base.html" %}
{% block content %}
<h2 align="left">Search Page</h2>
<form action="{% url 'render_results' %}" method="POST" >
{% csrf_token %}
<body>
<table>
<tr>
<td><b>Locations: </b></td>
<td>
<select name="location_name">
{% for locations in locations %}
<option value="{{locations.location_name}}">{{locations.location_name}}</option>{% endfor%}
</select>
</td>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
{% endblock content %}
render_results.html
<html>
<h2 align="left">Render Device List based on Location Choice</h2>
<b> Locations: </b><br>{{locations }} <br><br><br>
<b> Devices: </b><br>
{% for device in devices %}{{device.device_name}} <br>{% endfor %} </td>
<br>
<button type="submit" id="save">Save</button>
</html>
views.py
def render_results (request):
location_name = request.POST.get('location_name')
my_devices = Devices.objects.filter(locations = Locations.objects.get(location_name = location_name))
context = {"devices": my_devices,
"locations": location_name}
return render(request, 'inventory/render_results.html', context)
def search_device_list(request):
locations = Locations.objects.all()
print(locations)
context = {"locations": locations}
for locations in context['locations']:
print(locations)
location_name=request.POST.get('location_name')
if request.method == 'GET':
form = LocationsForm()
print(locations)
return render(request, 'inventory/search_device_list.html', context)
and finally urls.py
...
url(r'^search_device_list/$', views.search_device_list, name='search_device_list'),
url(r'^render_results/$', views.render_results, name='render_results'),
Do you have os.path.join(BASE_DIR, 'templates') set in your settings file?
This would be in the templates section. This code should replace the empty list for DIRS = []
https://docs.djangoproject.com/en/3.0/topics/templates/
This is just speculation of course. It would help to see the full settings.py and urls.py. Also as previous stated, make sure the path to your templates is app_name/templates/app_name/html_file
<form action="{% url 'inventory:render_results' %}" method="POST" >
If your getting NoReverseMatch Error simply means you have an issue with the URL pattern either on the HTML end or in the URLconf. The reserve URL tag in your HTML templates can just be {% url 'url_pattern_name' %}
The tag you were first using {% url 'inventory:render_results' %}. Indicates that Django is to go to your URL conf, find the namespaced urls ie. app_name = 'inventory'. Then search in the namespace to find render_results. You can use either configuration but again the latter is stating your URL is namepspaced with app_name='inventory'.
I am not entirely sure if you can use the non-namespaced HTML tag {url 'url_pattern_name'%} with a namespace url config ex.
https://docs.djangoproject.com/en/3.0/topics/http/urls/#reversing-namespaced-urls

Django Url does not work

I am trying to obtain a url to a view that renders an image so I can use it in an img tag with href.
But my {% url viewname object_id %} is not working. Here are the specifics:
my urls.py:
hydrourlpatterns = patterns('',
url(r'^graphs/$','hydro.views.graphs',name='graphs'),
url(r'^graphs/new/$', 'hydro.views.add_graph', name='add_graph'),
url(r'^graphs/(?P<graph_id>\d+?)/$', 'hydro.views.single_graph', name='graph_detail'),
url(r'^graphs/graphImage/(?P<graph_id>\d+?)/$', 'hydro.views.render_graph', name='graphImage')
)
my template(url: localhost/graphs/(graph_id)/):
{% extends "subpage.django" %}
{% block content %}
{% if graph %}
<h3> {{ graph.name }} </h3>
<h1> {% url 'graphImage' graph_id %} </h1>
{% endif %}
{% endblock %}
The error I keep getting is ViewDoesNotExsist.
Could not import hydro.views.add_site.
View does not exist in module hydro.views.
You use hydro.views.add_site somewhere else in your urls.py. Comment this url line or create add_site view in the hydro.views.
EDIT: You don't pass graph_id variable to the template so change {% url %} call to:
{% url 'graphImage' graph.id %}

conflict between User and user.socialaccount in django-allauth

I have done this tutorial as it explained here:
and here
but there is some points that i can not understand.
When i log in using a facebook account i can get access also easily to my admin page and i want it to be happened (because it is not secure), so is there a way to fix that ?
If i want to bring that registred user to another template, i can do it only whith direct_to_template method in my url dispatcher, here is an example:
url(r'^tags$', direct_to_template, {'template' : 'user.html' }),
is there another way to do it.
Finally to be more clear, here is some snippets of my project:
urls.py
urlpatterns = patterns('',
#All Auth URLS
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/profile/', direct_to_template, { 'template' : 'profile.html' }),
#nav urls
url(r'^$','fb.views.home', name="home"),
url(r'^tags$', direct_to_template, {'template' : 'tags.html' }),
views.py
def home(request):
return render_to_response("base.html", locals(), RequestContext(Context))
base.html
.....
{% block body %}
{% block content %}
{% if user.is_authenticated %}
{{ user.username }} <p> you are logged in </p>
<p><a href="/accounts/logout/" >Logout </a></p>
{% else %}
<p> you are not authenticated : </p>
<a href="/accounts/facebook/login/" >Login with Facebook </a>
{% endif %}
{% endblock content %}
{% endblock body %}
...
profile.html
...
{% block content %}
{% if user %}
<h1>Welcome, {{user.first_name}}</h1>
<p>Following is the Extra information that facebook has provided to allauth:</p>
{% for account in user.socialaccount_set.all %}
<p>First Name: {{ account.extra_data.first_name }}</p>
<p>Last Name: {{ account.extra_data.last_name }}</p>
<p>Profile Link: {{ account.extra_data.link }}</p>
{% endfor %}
{% endif %}
Go to tags
{% endblock content %}
{% endblock body %}
tags.html
{{user.socialaccount_set.all.0.get_avatar_url}} <br/>
{{user.socialaccount_set.all.0.uid}} <br/>
{{user.socialaccount_set.all.0.get_provider_account }} <br/>
Finally thanks in advance for your help .
The secrect is:
After logging in, the user was hiding in the request object, so view shoukd be like this:
def home(request):
user = request.user
return render_to_response("base.html", locals(), RequestContext(Context))
Now, the problem is resolved, but i wonder why the Context User object was anounymous.
i am asking this question because that last user object woiuld have the same value of the request user in a simple authentication

Navigation in django

I've just done my first little webapp in django and I love it. I'm about to start on converting an old production PHP site into django and as part its template, there is a navigation bar.
In PHP, I check each nav option's URL against the current URL, in the template code and apply a CSS class if they line up. It's horrendously messy.
Is there something better for django or a good way of handling the code in the template?
To start, how would I go about getting the current URL?
You do not need an if to do that, have a look at the following code:
tags.py
#register.simple_tag
def active(request, pattern):
import re
if re.search(pattern, request.path):
return 'active'
return ''
urls.py
urlpatterns += patterns('',
(r'/$', view_home_method, 'home_url_name'),
(r'/services/$', view_services_method, 'services_url_name'),
(r'/contact/$', view_contact_method, 'contact_url_name'),
)
base.html
{% load tags %}
{% url 'home_url_name' as home %}
{% url 'services_url_name' as services %}
{% url 'contact_url_name' as contact %}
<div id="navigation">
<a class="{% active request home %}" href="{{ home }}">Home</a>
<a class="{% active request services %}" href="{{ services }}">Services</a>
<a class="{% active request contact %}" href="{{ contact }}">Contact</a>
</div>
that's it.
for implementation details have a look at:
gnuvince.wordpress.com
110j.wordpress.com
I use template inheritance to customize navigation. For example:
base.html
<html>
<head>...</head>
<body>
...
{% block nav %}
<ul id="nav">
<li>{% block nav-home %}Home{% endblock %}</li>
<li>{% block nav-about %}About{% endblock %}</li>
<li>{% block nav-contact %}Contact{% endblock %}</li>
</ul>
{% endblock %}
...
</body>
</html>
about.html
{% extends "base.html" %}
{% block nav-about %}<strong class="nav-active">About</strong>{% endblock %}
I liked the cleanness of 110j above so I took most of it and refactored to solve the 3 problems I had with it:
the regular expression was
matching the 'home' url against all
others
I needed multiple URLs
mapped to one navigation tab, so I
needed a more complex tag that takes
variable amount of parameters
fixed some url problems
Here it is:
tags.py:
from django import template
register = template.Library()
#register.tag
def active(parser, token):
args = token.split_contents()
template_tag = args[0]
if len(args) < 2:
raise template.TemplateSyntaxError, "%r tag requires at least one argument" % template_tag
return NavSelectedNode(args[1:])
class NavSelectedNode(template.Node):
def __init__(self, patterns):
self.patterns = patterns
def render(self, context):
path = context['request'].path
for p in self.patterns:
pValue = template.Variable(p).resolve(context)
if path == pValue:
return "active" # change this if needed for other bootstrap version (compatible with 3.2)
return ""
urls.py:
urlpatterns += patterns('',
url(r'/$', view_home_method, {}, name='home_url_name'),
url(r'/services/$', view_services_method, {}, name='services_url_name'),
url(r'/contact/$', view_contact_method, {}, name='contact_url_name'),
url(r'/contact/$', view_contact2_method, {}, name='contact2_url_name'),
)
base.html:
{% load tags %}
{% url home_url_name as home %}
{% url services_url_name as services %}
{% url contact_url_name as contact %}
{% url contact2_url_name as contact2 %}
<div id="navigation">
<a class="{% active request home %}" href="home">Home</a>
<a class="{% active request services %}" href="services">Services</a>
<a class="{% active request contact contact2 %}" href="contact">Contact</a>
</div>
I'm the author of django-lineage which I wrote specifically to solve this question :D
I became annoyed using the (perfectly acceptable) jpwatts method in my own projects and drew inspiration from 110j's answer. Lineage looks like this:
{% load lineage %}
<div id="navigation">
<a class="{% ancestor '/home/' %}" href="/home/">Home</a>
<a class="{% ancestor '/services/' %}" href="/services/">Services</a>
<a class="{% ancestor '/contact/' %}" href="/contact/">Contact</a>
</div>
ancestor is simply replaced with "active" if the argument matches the start of current page URL.
Variable arguments, and full {% url %} type reverse resolution, is also supported. I sprinkled in a few configuration options and fleshed it out a little and packaged it up for everyone to use.
If anyone is interested, read a bit more about it at:
>> github.com/marcuswhybrow/django-lineage
Since Django 1.5:
In all generic class-based views (or any class-based view inheriting
from ContextMixin), the context dictionary contains a view variable
that points to the View instance.
So if you are using such views, you could add something likie breadcrumbs as a class level field and use it in your templates.
Example view code:
class YourDetailView(DetailView):
breadcrumbs = ['detail']
(...)
In your template you could use it in this way:
<a href="/detail/" {% if 'detail' in view.breadcrumbs %}class="active"{% endif %}>Detail</a>
If you want to additionally "highlight" parent navigation items, you need to extend breadcrumbs list:
class YourDetailView(DetailView):
breadcrumbs = ['dashboard', 'list', 'detail']
(...)
... and in your template:
<a href="/dashboard/" {% if 'dashboard' in view.breadcrumbs %}class="active"{% endif %}>Dashboard</a>
<a href="/list/" {% if 'list' in view.breadcrumbs %}class="active"{% endif %}>List</a>
<a href="/detail/" {% if 'detail' in view.breadcrumbs %}class="active"{% endif %}>Detail</a>
This is easy and clean solution and works pretty well with nested navigation.
You could apply a class or id to the body element of the page, rather than to a specific nav item.
HTML:
<body class="{{ nav_class }}">
CSS:
body.home #nav_home,
body.about #nav_about { */ Current nav styles */ }
I do it like this:
<a class="tab {% ifequal active_tab "statistics" %}active{% endifequal %}" href="{% url Member.Statistics %}">Statistics</a>
and then all I have to do is in my view add {'active_tab': 'statistics'} to my context dictionary.
If you are using RequestContext you can get current path in your template as:
{{ request.path }}
And in your view:
from django.template import RequestContext
def my_view(request):
# do something awesome here
return template.render(RequestContext(request, context_dict))
I took the code from nivhab above and removed some wierdness and made it into a clean templatetag, modified it so that /account/edit/ will still make /account/ tab active.
#current_nav.py
from django import template
register = template.Library()
#register.tag
def current_nav(parser, token):
import re
args = token.split_contents()
template_tag = args[0]
if len(args) < 2:
raise template.TemplateSyntaxError, "%r tag requires at least one argument" % template_tag
return NavSelectedNode(args[1])
class NavSelectedNode(template.Node):
def __init__(self, url):
self.url = url
def render(self, context):
path = context['request'].path
pValue = template.Variable(self.url).resolve(context)
if (pValue == '/' or pValue == '') and not (path == '/' or path == ''):
return ""
if path.startswith(pValue):
return ' class="current"'
return ""
#template.html
{% block nav %}
{% load current_nav %}
{% url home as home_url %}
{% url signup as signup_url %}
{% url auth_login as auth_login_url %}
<ul class="container">
<li>Home</li>
<li>Login</li>
<li>Signup</li>
</ul>
{% endblock %}
This is just a variant of the css solution proposed by Toba above:
Include the following in your base template:
<body id="section-{% block section %}home{% endblock %}">
Then in your templates that extend the base use:
{% block section %}show{% endblock %}
You can then use css to highlight the current area based on the body tag (for example if we have a link with an id of nav-home):
#section-home a#nav-home{
font-weight:bold;
}
You could use the reverse function with the appropriate parameters to get the current url.
Thanks for your answers so far, gents. I've gone for something slightly different again..
In my template:
<li{{ link1_active }}>...link...</li>
<li{{ link2_active }}>...link...</li>
<li{{ link3_active }}>...link...</li>
<li{{ link4_active }}>...link...</li>
Once I've worked out which page I'm on in the logic (usually in urls.py), I pass class="selected" as part of the context under the right name to the template.
Eg if I'm on the link1 page, I'll append {'link1_active':' class="selected"'} to the context for the template to scoop up and inject.
It appears to work and it's fairly clean.
Edit: to keep HTML out of my controller/view, I've modified this a bit:
<li{% if link1_active %} class="selected"{% endif %}>...link...</li>
<li{% if link2_active %} class="selected"{% endif %}>...link...</li>
...
It makes the template a little less readable, but I agree, it's better to not push through raw HTML from the urls file.
I found the best is to use an inclusion tag:
templates/fnf/nav_item.html
<li class="nav-item">
<a class="nav-link {% if is_active %}active{% endif %}" href="{% url url_name %}">{{ link_name }}</a>
</li>
This is just my basic bootstrap nav item I wish to render.
It gets the href value, and optionally the link_name value. is_active is calculated based on the current request.
templatetags/nav.py
from django import template
register = template.Library()
#register.inclusion_tag('fnf/nav_item.html', takes_context=True)
def nav_item(context, url_name, link_name=None):
return {
'url_name': url_name,
'link_name': link_name or url_name.title(),
'is_active': context.request.resolver_match.url_name == url_name,
}
Then use it in a nav:
templates/fnf/nav.html
{% load nav %}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<ul class="navbar-nav mr-auto">
{% nav_item 'dashboard' %}
</ul>
I have multiple menus on the same page that are created dynamically through a loop. The posts above relating to the context gave me a quick fix. Hope this helps somebody. (I use this in addition to the active template tag - my fix solves the dynamic issue). It seems like a silly comparison, but it works. I chose to name the variables active_something-unique and something-unique, this way it works with nested menus.
Here is a portion of the view (enough to understand what i am doing):
def project_list(request, catslug):
"render the category detail page"
category = get_object_or_404(Category, slug=catslug, site__id__exact=settings.SITE_ID)
context = {
'active_category':
category,
'category':
category,
'category_list':
Category.objects.filter(site__id__exact=settings.SITE_ID),
}
And this is from the template:
<ul>
{% for category in category_list %}
<li class="tab{% ifequal active_category category %}-active{% endifequal %}">
{{ category.cat }}
</li>
{% endfor %}
</ul>
My solution was to write a simple context processor to set a variable based on the request path:
def navigation(request):
"""
Custom context processor to set the navigation menu pointer.
"""
nav_pointer = ''
if request.path == '/':
nav_pointer = 'main'
elif request.path.startswith('/services/'):
nav_pointer = 'services'
elif request.path.startswith('/other_stuff/'):
nav_pointer = 'other_stuff'
return {'nav_pointer': nav_pointer}
(Don't forget to add your custom processor to TEMPLATE_CONTEXT_PROCESSORS in settings.py.)
Then in the base template I use an ifequal tag per link to determine whether to append the "active" class. Granted this approach is strictly limited to the flexibility of your path structure, but it works for my relatively modest deployment.
I just wanted to share my minor enhancement to nivhab's post. In my application I have subnavigations and I did not want to hide them using just CSS, so I needed some sort of "if" tag to display the subnavigation for an item or not.
from django import template
register = template.Library()
#register.tag
def ifnaviactive(parser, token):
nodelist = parser.parse(('endifnaviactive',))
parser.delete_first_token()
import re
args = token.split_contents()
template_tag = args[0]
if len(args) < 2:
raise template.TemplateSyntaxError, "%r tag requires at least one argument" % template_tag
return NavSelectedNode(args[1:], nodelist)
class NavSelectedNode(template.Node):
def __init__(self, patterns, nodelist):
self.patterns = patterns
self.nodelist = nodelist
def render(self, context):
path = context['request'].path
for p in self.patterns:
pValue = template.Variable(p).resolve(context)
if path == pValue:
return self.nodelist.render(context)
return ""
You can use this basically in the same way as the active tag:
{% url product_url as product %}
{% ifnaviactive request product %}
<ul class="subnavi">
<li>Subnavi item for product 1</li>
...
</ul>
{% endifnaviactive %}
Just another ehnancement of the original solution.
This accept multiple patterns and which is best also unnamed patterns written as relative URL wrapped in '"', like following:
{% url admin:clients_client_changelist as clients %}
{% url admin:clients_town_changelist as towns %}
{% url admin:clients_district_changelist as districts %}
<li class="{% active "/" %}">Home</li>
<li class="{% active clients %}">Clients</li>
{% if request.user.is_superuser %}
<li class="{% active towns districts %}">
Settings
<ul>
<li>Towns</li>
<li>Districts</li>
</ul>
</li>
{% endif %}
Tag goes like this:
from django import template
register = template.Library()
#register.tag
def active(parser, token):
args = token.split_contents()
template_tag = args[0]
if len(args) < 2:
raise template.TemplateSyntaxError, "%r tag requires at least one argument" % template_tag
return NavSelectedNode(args[1:])
class NavSelectedNode(template.Node):
def __init__(self, urls):
self.urls = urls
def render(self, context):
path = context['request'].path
for url in self.urls:
if '"' not in url:
cpath = template.Variable(url).resolve(context)
else:
cpath = url.strip('"')
if (cpath == '/' or cpath == '') and not (path == '/' or path == ''):
return ""
if path.startswith(cpath):
return 'active'
return ""
I used jquery to highlight my navbars. This solution simply adds the css class "active" to the item which fits the css selector.
<script type="text/javascript" src="/static/js/jquery.js"></script>
<script>
$(document).ready(function(){
var path = location.pathname;
$('ul.navbar a.nav[href$="' + path + '"]').addClass("active");
});
</script>
A little enhancement over #tback's answer, without any %if% tags:
# navigation.py
from django import template
from django.core.urlresolvers import resolve
register = template.Library()
#register.filter(name="activate_if_active", is_safe=True)
def activate_if_active(request, urlname):
if resolve(request.get_full_path()).url_name == urlname:
return "active"
return ''
Use it in your template like that:
{% load navigation %}
<li class="{{ request|activate_if_active:'url_name' }}">
My View
</li>
And include "django.core.context_processors.request" in your TEMPLATE_CONTEXT_PROCESSORS setting.
Inspired by this solution, I started to use this approach:
**Placed in templates as base.html**
{% block tab_menu %}
<ul class="tab-menu">
<li class="{% if active_tab == 'tab1' %} active{% endif %}">Tab 1</li>
<li class="{% if active_tab == 'tab2' %} active{% endif %}">Tab 2</li>
<li class="{% if active_tab == 'tab3' %} active{% endif %}">Tab 3</li>
</ul>
{% endblock tab_menu %}
**Placed in your page template**
{% extends "base.html" %}
{% block tab_menu %}
{% with active_tab="tab1" %} {{ block.super }} {% endwith %}
{% endblock tab_menu %}
Slightly modifying Andreas' answer, it looks like you can pass in the name of the route from urls.py to the template tag. In my example my_tasks, and then in the template tag function use the reverse function to work out what the URL should be, then you can match that against the URL in the request object (available in the template context)
from django import template
from django.core.urlresolvers import reverse
register = template.Library()
#register.tag
def active(parser, token):
args = token.split_contents()
template_tag = args[0]
if len(args) < 2:
raise template.TemplateSyntaxError, "%r tag requires at least one argument" % template_tag
return NavSelectedNode(args[1:])
class NavSelectedNode(template.Node):
def __init__(self, name):
self.name = name
def render(self, context):
if context['request'].path == reverse(self.name[1]):
return 'active'
else:
return ''
urls.py
url(r'^tasks/my', my_tasks, name = 'my_tasks' ),
template.html
<li class="{% active request all_tasks %}">Everyone</li>
I know I'm late to the party. I didn't like any of the popular solutions though:
The block method seems wrong: I think the navigation should be self contained.
The template_tag method seems wrong: I don't like that I have to get the url from the url-tag first. Also, I think the css-class should be defined in the template, not the tag.
I therefore wrote a filter that doesn't have the drawbacks I described above. It returns True if a url is active and can therefore be used with {% if %}:
{% load navigation %}
<li{% if request|active:"home" %} class="active"{% endif %}>Home</li>
The code:
#register.filter(name="active")
def active(request, url_name):
return resolve(request.path_info).url_name == url_name
Just make sure to use RequestContext on pages with navigation or to enable the request context_processor in your settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.request',
)
I've seen jpwatts', 110j's, nivhab's & Marcus Whybrow's answers, but they all seem to lack in something: what about the root path ? Why it's always active ?
So I've made an other way, easier, which make the "controller" decides by itself and I think it resolve most of the big problems.
Here is my custom tag:
## myapp_tags.py
#register.simple_tag
def nav_css_class(page_class):
if not page_class:
return ""
else:
return page_class
Then, the "controller" declares CSS classes needed (in fact, the most important is it declares its presence to the template)
## views.py
def ping(request):
context={}
context["nav_ping"] = "active"
return render(request, 'myapp/ping.html',context)
And finally, I render it in my navigation bar:
<!-- sidebar.html -->
{% load myapp_tags %}
...
<a class="{% nav_css_class nav_home %}" href="{% url 'index' %}">
Accueil
</a>
<a class="{% nav_css_class nav_candidats %}" href="{% url 'candidats' %}">
Candidats
</a>
<a class="{% nav_css_class nav_ping %}" href="{% url 'ping' %}">
Ping
</a>
<a class="{% nav_css_class nav_stat %}" href="{% url 'statistiques' %}">
Statistiques
</a>
...
So each page has its own nav_css_class value to set, and if it's set, the template renders active: no need of request in template context, no URL parcing and no more problems about multi-URL pages or root page.
Here's my go at it. I ended up implementing a class in my views that contains my navigation structure (flat with some metadata). I then inject this to the template and render it out.
My solution deals with i18n. It probably should be abstracted out a bit more but I haven't really bothered with that really.
views.py:
from django.utils.translation import get_language, ugettext as _
class Navi(list):
items = (_('Events'), _('Users'), )
def __init__(self, cur_path):
lang = get_language()
first_part = '/' + cur_path.lstrip('/').split('/')[0]
def set_status(n):
if n['url'] == first_part:
n['status'] == 'active'
for i in self.items:
o = {'name': i, 'url': '/' + slugify(i)}
set_status(o)
self.append(o)
# remember to attach Navi() to your template context!
# ie. 'navi': Navi(request.path)
I defined the template logic using includes like this. Base template:
{% include "includes/navigation.html" with items=navi %}
Actual include (includes/navigation.html):
<ul class="nav">
{% for item in items %}
<li class="{{ item.status }}">
{{ item.name }}
</li>
{% endfor %}
</ul>
Hopefully someone will find this useful! I guess it would be pretty easy to extend that idea to support nested hierarchies etc.
Create an include template "intranet/nav_item.html":
{% load url from future %}
{% url view as view_url %}
<li class="nav-item{% ifequal view_url request.path %} current{% endifequal %}">
{{ title }}
</li>
And include it in the nav element:
<ul>
{% include "intranet/nav_item.html" with view='intranet.views.home' title='Home' %}
{% include "intranet/nav_item.html" with view='crm.views.clients' title='Clients' %}
</ul>
And you need to add this to settings:
from django.conf import global_settings
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
'django.core.context_processors.request',
)
here is pretty simple solution, https://github.com/hellysmile/django-activeurl
from this SO Question
{% url 'some_urlpattern_name' as url %}
<a href="{{url}}"{% if request.path == url %} class="active"{% endif %}>Link</a>
Repeat as necessary for each link.
I also used jQuery to highlight it and find it more elegant than cluttering the template with non-semantic Django template tags.
The code below works with nested dropdowns in bootstrap 3 (highlights both the parent, and the child <li> element.
// DOM Ready
$(function() {
// Highlight current page in nav bar
$('.nav, .navbar-nav li').each(function() {
// Count the number of links to the current page in the <li>
var matched_links = $(this).find('a[href]').filter(function() {
return $(this).attr('href') == window.location.pathname;
}).length;
// If there's at least one, mark the <li> as active
if (matched_links)
$(this).addClass('active');
});
});
It's also quite easy to add a click event to return false (or change the href attribute to #) for the current page, without changing the template/html markup:
var matched_links = $(this).find('a[href]').filter(function() {
var matched = $(this).attr('href') == window.location.pathname;
if (matched)
$(this).click(function() { return false; });
return matched;
}).length;
I use a combination of this mixin for class based views:
class SetActiveViewMixin(object):
def get_context_data(self, **kwargs):
context = super(SetActiveViewMixin, self).get_context_data(**kwargs)
context['active_nav_menu'] = {
self.request.resolver_match.view_name: ' class="pure-menu-selected"'
}
return context
with this in the template:
<ul>
<li{{active_nav_menu.node_explorer }}>Explore</li>
<li{{active_nav_menu.node_create }}>Create</li>
<li{{active_nav_menu.node_edit }}>Edit</li>
<li{{active_nav_menu.node_delete }}>Delete</li>
</ul>
Mine is a bit similar to another JS approach submitted previously.. just without jQuery...
Say we have in base.html the following:
<div class="pure-u-1 pure-menu pure-menu-open pure-menu-horizontal header" >
<ul class="">
<li id="home">Home</li>
<li id="news">News</li>
<li id="analysis">Analysis</li>
<li id="opinion">Opinion</li>
<li id="data">Data</li>
<li id="events">Events</li>
<li id="forum">Forum</li>
<li id="subscribe">Subscribe</li>
</ul>
<script type="text/javascript">
(function(){
loc=/\w+/.exec(window.location.pathname)[0];
el=document.getElementById(loc).className='pure-menu-selected';
})();
</script>
</div>
I just made my hierarchy to follow a certain URL pattern... after the host address... i have my main category, eg, home, news, analysis, etc. and the regex just pulls the first word out of the location
**
Just add url and name in jinja format like this
**
<ul class="nav navbar-nav">
<li>
Cities
</li>
<li>
Cafes
</li>
</ul>