How do I access unrelated models within a Django template? - django

I want to use an app to create a menu that is easy to edit with the admin interface. Something like this:
class Menu_item
name = models.CharField()
item_url = models.URLField()
My template looks something like this:
{% extends base.html %}
div ID="nav"
{{ foo.navbar.? }}
/div
div ID="Content"
{% block content %}{% endblock %}
/div
I want div#nav to contain a ul based upon the above model but just can't figure out how to accomplish this. It seems like an object_list generic view would be great but, the URL accesses the view for the model that populates div#content. Does anyone have any suggestions? Is there a way to access a generic view without a URL?
Thank you.

I have discovered a solution. Inclusion Tags.
What I did was create an inclusion tag, which amounts to a simple custom template tag (django provides a shortcut for you!).
Here is what I did:
Ignore views.py - It will not be used in this case
Create a sub-directory in the app's dir called "templatetags" containing init.py and get_navbar.py (or whatever you want your tag to be):
mysite/
navbar/
templatetags/
__ init__.py (without the space befire init)
get_navbar.py
I changed my navbar.models to look like this:
from django.db import models
class Menu_choice(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Menu_item(models.Model):
name = models.CharField(max_length=20)
navbar = models.ForeignKey(Menu_choice)
item_url = models.CharField(max_length=200)
item_desc = models.CharField(max_length=30)
def __unicode__(self):
return self.name
This allows me to create a Menu_choice object in the admin interface for each layer of navigation (primary, secondary, etc)
get_navbar.py looks like this:
from navbar.models import Menu_choice, Menu_item
from django import template
register = template.Library()
#register.inclusion_tag('navbar/navbar.html')
def get_navbar(navBar):
navbar = Menu_item.objects.filter(navbar__name=navBar)
return { "navbar": navbar }
(Note navBar as opposed to navbar)
Create the navbar.html template:
<ul>
{% for menu_item in navbar %}
<li><a href="{{ menu_item.item_url }}">{{ menu_item.name }}&lt/a>&lt/li>
{% endfor %}
</ul>
Finally, I inserted the following into my base.html:
{% load get_navbar %}
And where I want primary navigation:
{% get_navbar "primary" %}
Note: the quotes around the string you are sending to your inclusion tag are important. I spent a ridiculously lengthy bit of time trying to make it work before I figured that out.
Also a big thank you to dikamilo for the help.

First, in you view, get data from db:
def index(request):
navbar = Menu_item.objects.all()
return render_to_response( 'you_template.html',
{ 'navbar': navbar }, context_instance = RequestContext (request ) )
And in template:
<div id="nav">
<ul>
{% for i in navbar %}
<li>{{ i.name }}</li>
{% endfor %}
</ul>
</div>

Related

How can i make a certain template visible only to confirmed users in Django?

I'm creating a site and I successfully added an email confirmation system using django-allauth. Now I would like to have some parts of my site available only to users who confirmed their email.
Suppose that part looks something like this:
{% extends "main/header.html" %}
{% if user.is_authenticated %}
{% block content %}
<body>
<div>
<p> Here are are a bunch of features etc... </p>
</div>
</body>
{% endblock %}
{% endif %}
Now, I know how to do that in theory, but not practically. I figured that I need to add a statement that checks if the email is confirmed. What I'm not understanding is where should I add this statement and what that should look like. Should it be on the template? Or should I create a view for this? Any advice is appreciated? Thanks in advance!
I think its best to put the login in your CustomUser Model:
class CustomUser(AbstractUser):
#property
def has_verified_email(self):
return self.emailaddress_set.filter(verified=True,primary=True).exists()
Then use in template:
{% if user.has_verified_email %}
// some lines
{% endif %}
If you haven't overridden your User model, then you can put it in a separate model which has a OneToOne relation to your User model:
class Profile(models.Model):
user = models.OneToOneField(User)
#property
def has_verified_email(self):
return self.user.emailaddress_set.filter(verified=True,primary=True).exists()
Then use it in template:
{% if user.profile.has_verified_email %}
// some lines
{% endif %}
Second best option would be to use in View, but you will need to put the same logic in every view. If you are using a Class Based View, you can make a Mixin and use it in them:
class SomeMixin(object):
def get_context_data(self, *args, **kwargs):
context = super(SomeMixin, self).get_context_data(*args, **kwargs)
context['has_verified_email'] = self.request.user.emailaddress_set.filter(verified=True,primary=True).exists()
return context
class ActualView(SomeMixin, TemplateView):
# subclassing from the mixin in
// template code
{% if has_verified_email %}
// some lines
{% endif %}

How to translate all the contents inside model queries in DJango?

i am a new to Django, i am trying to make a small blog with two different languages, i got all the translations inside my blog including the admin, but still don't know how to translate the content of my posts.
After i fetch the content using the models queries, inside my template i used to type this {% trans "SOME TEXT" %} and it works just fine, with variables that i am getting from database i am using this code:
{% blocktrans %}
{{head.title_text}}
{% endblocktrans %}
now when i type django-admin makemessages -l ru, inside django.po i can't see any new text that have been added.
Also inside my views.py i tried this:
head = Head.objects.first()
trans_h = _(u'{}'.format(head))
but nothing gets added inside django.po
Please, anyone knows how to resolve this issue ??
I think the best way to translate the content of the Post Model without using any third-party is to create for each fields you need to translate inside your models with different languages and translate them from your admin,and display them in your template when the site change the language, in Django you can translate only the text you can not translate the data from your model
Create your model Post
models.py
class Post(models.Model)
title_fr = models.CharField(max_length=200)
title_en = models.CharField(max_length=200)
content_fr = models.TextField()
content_en = models.TextField()
created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)
In the view you translate the text inside the variable and pass it in your template
views.py
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from .models import Post
from django.utils.translation import ugettext_lazy as _
def post_view(request):
post = Post.objects.all()
# Here is you can translate the text in python
title = _("les meilleurs posts du mois")
context = {
'post':post,
'title':title
}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
Here the idea is once your site is translated in french for example(www.mysite.com/fr/) in your template you will get only the attributes with _fr(title_fr, content_fr) already translated in your admin and if it's in english it will be the same thing
index.html
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_available_languages as LANGUAGES %}
<h1> {{ title}}</h1>
{% if LANGUAGE_CODE|language_name_translated == 'Français' %}
{% for items in home %}
<h2>{{ items.title_fr }}</h2>
<p> {{items.content_fr}}</p>
{% endfor %}
{% if LANGUAGE_CODE|language_name_translated == 'English' %}
{% for items in home %}
<h2>{{ items.title_en }}</h2>
<p>{{items.content_en}}</p>
{% endfor %}
{% endif %}
I hope it can be helpful

How can I add a button into django admin change list view page

I would like to add a button next to "add" button in list view in model for my model and then create a view function where I will do my stuff and then redirect user back to list view.
I've checked how to overload admin template, but I still dont know, where should I put my view function where I will do my stuff, and how can I register that view into admin urls.
There is also question about security. I would like to have that action inside admin, so if u r not logged in, u cannot use it.
I've found this, but I don't know if it's the right way: http://www.stavros.io/posts/how-to-extend-the-django-admin-site-with-custom/
When several applications provide different versions of the same
resource (template, static file, management command, translation), the
application listed first in INSTALLED_APPS has precedence.
- Django documentation on INSTALLED_APPS
Make sure your app is listed before 'django.contrib.admin' in INSTALLED_APPS.
Create a change_list.html template in one of the following directories:
# Template applies to all change lists.
myproject/myapp/templates/admin/change_list.html
# Template applies to change lists in myapp.
myproject/myapp/templates/admin/myapp/change_list.html
# Template applies to change list in myapp and only to the Foo model.
myproject/myapp/templates/admin/myapp/foo/change_list.html
The template should be picked up automatically, but in case it is not on one of paths listed above, you can also point to it via an admin model attribute:
class MyModelAdmin(admin.ModelAdmin):
#...
change_list_template = "path/to/change_list.html"
You can lookup the contents of the original change_list.html it lives in path/to/your/site-packages/django/contrib/admin/templates/admin/change_list.html. The other answer also shows you how to format the template. Nikolai Saiko shows you how to override the relevant parts using 'extends' and 'super'. Summary:
{% extends "admin/change_list.html" %} {% load i18n %}
{% block object-tools-items %}
{{ block.super }}
<li>
<a class="historylink" href="...">My custom admin page</a>
</li>
{% endblock %}
Let's fill href="..." with an url. The admin url names are in the namespace 'admin' and can be looked up like this:
{% url 'admin:custom_view' %}
When you are adding a button to change_form.html you maybe want to pass in the current object id:
{% url 'admin:custom_view' original.pk %}
Now create a custom view. This can be a regular view (just like other pages on your website) or a custom admin view in admin.py. The get_urls method on a ModelAdmin returns the URLs to be used for that ModelAdmin in the same way as a URLconf. Therefore you can extend them as documented in URL dispatcher:
class MyModelAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super(MyModelAdmin, self).get_urls()
my_urls = patterns('',
url(r'^my_view/$', self.my_view, name="custom_view")
)
return my_urls + urls
def my_view(self, request):
# custom view which should return an HttpResponse
pass
# In case your template resides in a non-standard location
change_list_template = "path/to/change_list.html"
Read the docs on how to set permissions on a view in ModelAdmin: https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls
You can protect your view and only give access to users with staff status:
from django.contrib.admin.views.decorators import staff_member_required
#staff_member_required
def my_view(request):
...
You might also want to check request.user.is_active and handle inactive users.
Update: Take advantage of the framework and customise as little as possible. Many times actions can be a good alternative: https://docs.djangoproject.com/en/1.5/ref/contrib/admin/actions/
Update 2: I removed a JS example to inject a button client side. If you need it, see the revisions.
Here is another solution , without using of jQuery (like one provided by allcaps). Also this solution provides object's pk with more intuitive way :)
I'll give my source code based on that link (follow link above for more info):
I have an app Products with model Product. This code adds button "Do Evil", which executes ProductAdmin.do_evil_view()
File products/models.py:
class ProductAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super().get_urls()
my_urls = patterns('',
(r'^(?P<pk>\d+)/evilUrl/$', self.admin_site.admin_view(self.do_evil_view))
)
return my_urls + urls
def do_evil_view(self, request, pk):
print('doing evil with', Product.objects.get(pk=int(pk)))
return redirect('/admin/products/product/%s/' % pk)
self.admin_site.admin_view is needed to ensure that user was logged as administrator.
And this is template extention of standard Django admin page for changing entry:
File: {template_dir}/admin/products/product/change_form.html
In Django >= 1.8 (thanks to #jenniwren for this info):
{% extends "admin/change_form.html" %}
{% load i18n %}
{% block object-tools-items %}
{{ block.super }}
<li><a class="historylink" href="evilUrl/">{% trans "Do Evil" %}</a></li>
{% endblock %}
If your Django version is lesser than 1.8, you have to write some more code:
{% extends "admin/change_form.html" %}
{% load i18n %}
{% block object-tools %}
{% if change %}{% if not is_popup %}
<ul class="object-tools">
<li><a class="historylink" href="history/">{% trans "History" %}</a></li>
<li><a class="historylink" href="evilUrl/">{% trans "Do Evil" %}</a></li>
{% if has_absolute_url %}
<li><a class="viewsitelink" href="../../../r/{{ content_type_id }}/{{ object_id }}/">{% trans "View on site" %}</a></li>
{% endif%}</ul>
{% endif %}{% endif %}
{% endblock %}

How to use one view on two different pages in Django?

I'm building a site with Django 1.5.1. I have Album and Category models defined:
###models.py
class Category(models.Model):
title = models.CharField(max_length=200, unique=True)
class Album(models.Model):
category = models.ForeignKey(Category, related_name='albums')
I've generated a menu to list automatically Categories and their related Albums with this view and template:
###views.py
def index(request):
categories = Category.objects.all()[:5]
context = {'categories': categories}
return render(request, 'gallery/index.html', context)
def detail(request, album_id):
album = get_object_or_404(Album, pk=album_id)
return render(request, 'gallery/detail.html', {'album': album})
###index.html
{% for category in categories %}
{% with category.albums.all as albums %}
{{ category.title }}
{% if albums %}
{% for album in albums %}
{{ album.title }}<br>
{% endfor %}
{% endif %}
{% endwith %}
{% endfor %}
Biography
I also have a view to show each album as a gallery indicates to detail.html. I want to show menu list beside each gallery so I used {% include "gallery/index.html" %} tag at the begining of detail.html. But menu list doesn't show up when detail.html loads, I just see Biography fixed link.
Here is my question: How should I import menu list generated in index.html in detail.html too?
index.html expects to receive categories variable in order to create the menu. If you want to include it in some other template you have to pass the categories variable to the other template for the included one. If you have some conflicts with names you can also pass variables to the include tag like this:
{% include 'include_template.html' with foo=bar%}
So the included template can use the variable foo which has the value bar.
For example, you need to pass the categories variable to the context generating for the detail.html like this:
def detail(request, album_id):
categories = Category.objects.all()[:5]
album = get_object_or_404(Album, pk=album_id)
return render(request,
'gallery/detail.html',
{'album': album,
'categories':categories}
)
And the line that includes the index.html template inside the detail.html template should remain like it is in the question:
{% include "gallery/index.html" %}
What I just did was pass the categories variable needed by index.html for rendering the menu to the detail.html template, which in turn, will pass it to all included template (index.html).
That should get the menu working from within detail.html template.
Hope it helps.

How to implement breadcrumbs in a Django template?

Some solutions provided on doing a Google search for "Django breadcrumbs" include using templates and block.super, basically just extending the base blocks and adding the current page to it. http://www.martin-geber.com/thought/2007/10/25/breadcrumbs-django-templates/
http://www.djangosnippets.org/snippets/1289/ - provides a template tag but I'm not sure this would work if you don't have your urls.py properly declared.
I'm wondering what's the best way? And if you have implemented breadcrumbs before how did you do it?
--- Edit --
My question was meant to be: is there a general accepted method of doing breadcrumbs in Django, but from the answers I see there is not, and there are many different solutions, I'm not sure who to award the correct answer to, as I used a variation of using the block.super method, while all the below answers would work.
I guess then this is too much of a subjective question.
Note: I provide the full snippet below, since djangosnippets has been finicky lately.
Cool, someone actually found my snippet :-) The use of my template tag is rather simple.
To answer your question there is no "built-in" django mechanism for dealing with breadcrumbs, but it does provide us with the next best thing: custom template tags.
Imagine you want to have breadcrumbs like so:
Services -> Programming
Services -> Consulting
Then you will probably have a few named urls: "services", and "programming", "consulting":
(r'^services/$',
'core.views.services',
{},
'services'),
(r'^services/programming$',
'core.views.programming',
{},
'programming'),
(r'^services/consulting$',
'core.views.consulting',
{},
'consulting'),
Now inside your html template (lets just look at consulting page) all you have to put is:
//consulting.html
{% load breadcrumbs %}
{% block breadcrumbs %}
{% breadcrumb_url 'Services' services %}
{% breadcrumb_url 'Consulting' consulting %}
{% endblock %}
If you want to use some kind of custom text within the breadcrumb, and don't want to link it, you can use breadcrumb tag instead.
//consulting.html
{% load breadcrumbs %}
{% block breadcrumbs %}
{% breadcrumb_url 'Services' services %}
{% breadcrumb_url 'Consulting' consulting %}
{% breadcrumb 'We are great!' %}
{% endblock %}
There are more involved situations where you might want to include an id of a particular object, which is also easy to do. This is an example that is more realistic:
{% load breadcrumbs %}
{% block breadcrumbs %}
{% breadcrumb_url 'Employees' employee_list %}
{% if employee.id %}
{% breadcrumb_url employee.company.name company_detail employee.company.id %}
{% breadcrumb_url employee.full_name employee_detail employee.id %}
{% breadcrumb 'Edit Employee ' %}
{% else %}
{% breadcrumb 'New Employee' %}
{% endif %}
{% endblock %}
DaGood breadcrumbs snippet
Provides two template tags to use in your HTML templates: breadcrumb and breadcrumb_url. The first allows creating of simple url, with the text portion and url portion. Or only unlinked text (as the last item in breadcrumb trail for example). The second, can actually take the named url with arguments! Additionally it takes a title as the first argument.
This is a templatetag file that should go into your /templatetags directory.
Just change the path of the image in the method create_crumb and you are good to go!
Don't forget to {% load breadcrumbs %} at the top of your html template!
from django import template
from django.template import loader, Node, Variable
from django.utils.encoding import smart_str, smart_unicode
from django.template.defaulttags import url
from django.template import VariableDoesNotExist
register = template.Library()
#register.tag
def breadcrumb(parser, token):
"""
Renders the breadcrumb.
Examples:
{% breadcrumb "Title of breadcrumb" url_var %}
{% breadcrumb context_var url_var %}
{% breadcrumb "Just the title" %}
{% breadcrumb just_context_var %}
Parameters:
-First parameter is the title of the crumb,
-Second (optional) parameter is the url variable to link to, produced by url tag, i.e.:
{% url person_detail object.id as person_url %}
then:
{% breadcrumb person.name person_url %}
#author Andriy Drozdyuk
"""
return BreadcrumbNode(token.split_contents()[1:])
#register.tag
def breadcrumb_url(parser, token):
"""
Same as breadcrumb
but instead of url context variable takes in all the
arguments URL tag takes.
{% breadcrumb "Title of breadcrumb" person_detail person.id %}
{% breadcrumb person.name person_detail person.id %}
"""
bits = token.split_contents()
if len(bits)==2:
return breadcrumb(parser, token)
# Extract our extra title parameter
title = bits.pop(1)
token.contents = ' '.join(bits)
url_node = url(parser, token)
return UrlBreadcrumbNode(title, url_node)
class BreadcrumbNode(Node):
def __init__(self, vars):
"""
First var is title, second var is url context variable
"""
self.vars = map(Variable,vars)
def render(self, context):
title = self.vars[0].var
if title.find("'")==-1 and title.find('"')==-1:
try:
val = self.vars[0]
title = val.resolve(context)
except:
title = ''
else:
title=title.strip("'").strip('"')
title=smart_unicode(title)
url = None
if len(self.vars)>1:
val = self.vars[1]
try:
url = val.resolve(context)
except VariableDoesNotExist:
print 'URL does not exist', val
url = None
return create_crumb(title, url)
class UrlBreadcrumbNode(Node):
def __init__(self, title, url_node):
self.title = Variable(title)
self.url_node = url_node
def render(self, context):
title = self.title.var
if title.find("'")==-1 and title.find('"')==-1:
try:
val = self.title
title = val.resolve(context)
except:
title = ''
else:
title=title.strip("'").strip('"')
title=smart_unicode(title)
url = self.url_node.render(context)
return create_crumb(title, url)
def create_crumb(title, url=None):
"""
Helper function
"""
crumb = """<span class="breadcrumbs-arrow">""" \
"""<img src="/media/images/arrow.gif" alt="Arrow">""" \
"""</span>"""
if url:
crumb = "%s<a href='%s'>%s</a>" % (crumb, url, title)
else:
crumb = "%s %s" % (crumb, title)
return crumb
The Django admin view modules have automatic breadcumbs, which are implemented like this:
{% block breadcrumbs %}
<div class="breadcrumbs">
{% trans 'Home' %}
{% block crumbs %}
{% if title %} › {{ title }}{% endif %}
{% endblock %}
</div>
{% endblock %}
So there is some kind of built-in support for this..
My view functions emit the breadcrumbs as a simple list.
Some information is kept in the user's session. Indirectly, however, it comes from the URL's.
Breadcrumbs are not a simple linear list of where they've been -- that's what browser history is for. A simple list of where they've been doesn't make a good breadcrumb trail because it doesn't reflect any meaning.
For most of our view functions, the navigation is pretty fixed, and based on template/view/URL design. In our cases, there's a lot of drilling into details, and the breadcrumbs reflect that narrowing -- we have a "realm", a "list", a "parent" and a "child". They form a simple hierarchy from general to specific.
In most cases, a well-defined URL can be trivially broken into a nice trail of breadcrumbs. Indeed, that's one test for good URL design -- the URL can be interpreted as breadcrumbs and displayed meaningfully to the users.
For a few view functions, where we present information that's part of a "many-to-many" join, for example, there are two candidate parents. The URL may say one thing, but the session's context stack says another.
For that reason, our view functions have to leave context clues in the session so we can emit breadcrumbs.
Try django-breadcrumbs — a pluggable middleware that add a breadcrumbs callable/iterable in your request object.
It supports simple views, generic views and Django FlatPages app.
I had the same issue and finally I've made simple django tempalate tag for it: https://github.com/prymitive/bootstrap-breadcrumbs
http://www.djangosnippets.org/snippets/1289/ - provides a template tag but i'm not sure this would work if you don't have your urls.py properly declared.
Nothing will work if you don't have your urls.py properly declared. Having said that, it doesn't look as though it imports from urls.py. In fact, it looks like to properly use that tag, you still have to pass the template some variables. Okay, that's not quite true: indirectly through the default url tag, which the breadcrumb tag calls. But as far as I can figure, it doesn't even actually call that tag; all occurrences of url are locally created variables.
But I'm no expert at parsing template tag definitions. So say somewhere else in the code it magically replicates the functionality of the url tag. The usage seems to be that you pass in arguments to a reverse lookup. Again, no matter what your project is, you urls.py should be configured so that any view can be reached with a reverse lookup. This is especially true with breadcrumbs. Think about it:
home > accounts > my account
Should accounts, ever hold an arbitrary, hardcoded url? Could "my account" ever hold an arbitrary, hardcoded url? Some way, somehow you're going to write breadcrumbs in such a way that your urls.py gets reversed. That's really only going to happen in one of two places: in your view, with a call to reverse, or in the template, with a call to a template tag that mimics the functionality of reverse. There may be reasons to prefer the former over the latter (into which the linked snippet locks you), but avoiding a logical configuration of your urls.py file is not one of them.
Try django-mptt.
Utilities for implementing Modified Preorder Tree Traversal (MPTT) with your Django Model classes and working with trees of Model instances.
This answer is just the same as #Andriy Drozdyuk (link). I just want to edit something so it works in Django 3.2 (in my case) and good in bootstrap too.
for create_crumb function (Remove the ">" bug in the current code)
def create_crumb(title, url=None):
"""
Helper function
"""
if url:
crumb = '<li class="breadcrumb-item">{}</li>'.format(url, title)
else:
crumb = '<li class="breadcrumb-item active" aria-current="page">{}</li>'.format(title)
return crumb
And for __init__ in BreadcrumbNode, add list() to make it subscriptable. And change smart_unicode to smart_text in render method
from django.utils.encoding import smart_text
class BreadcrumbNode(Node):
def __init__(self, vars):
"""
First var is title, second var is url context variable
"""
self.vars = list(map(Variable, vars))
def render(self, context):
title = self.vars[0].var
if title.find("'")==-1 and title.find('"')==-1:
try:
val = self.vars[0]
title = val.resolve(context)
except:
title = ''
else:
title=title.strip("'").strip('"')
title=smart_text(title)
And add this in base.html for the view for Bootstrap. Check the docs
<nav style="--bs-breadcrumb-divider: '>';" aria-label="breadcrumb">
<ol class="breadcrumb">
{% block breadcrumbs %}
{% endblock breadcrumbs %}
</ol>
</nav>
Obviously, no one best answer, but for practical reason I find that it is worth considering the naïve way. Just overwrite and rewrite the whole breadcrumb... (at least until the official django.contrib.breadcrumb released )
Without being too fancy, it is better to keep things simple. It helps the newcomer to understand. It is extremely customizable (e.g. permission checking, breadcrumb icon, separator characters, active breadcrumb, etc...)
Base Template
<!-- File: base.html -->
<html>
<body>
{% block breadcrumb %}
<ul class="breadcrumb">
<li>Dashboard</li>
</ul>
{% endblock breadcrumb %}
{% block content %}{% endblock content %}
</body>
</html>
Implementation Template
Later on each pages we rewrite and overwrite the whole breadcrumb block.
<!-- File: page.html -->
{% extends 'base.html' %}
{% block breadcrumb %}
<ul class="breadcrumb">
<li>Dashboard</li>
<li>Level 1</li>
<li class="active">Level 2</li>
</ul>
{% endblock breadcrumb %}
Practicallity
Realworld use cases:
Django Oscar: base template, simple bread
Django Admin: base template, simple bread, permission check breadcrumb
You could also reduce the boiler plate required to manage breadcrumbs using django-view-breadcrumbs, by adding a crumbs property to the view.
urls.py
urlpatterns = [
...
path('posts/<slug:slug>', views.PostDetail.as_view(), name='post_detail'),
...
]
views.py
from django.views.generic import DetailView
from view_breadcrumbs import DetailBreadcrumbMixin
class PostDetail(DetailBreadcrumbMixin, DetailView):
model = Post
template_name = 'app/post/detail.html'
base.html
{% load django_bootstrap_breadcrumbs %}
{% block breadcrumbs %}
{% render_breadcrumbs %}
{% endblock %}
Something like this may work for your situation:
Capture the entire URL in your view and make links from it. This will require modifying your urls.py, each view that needs to have breadcrumbs, and your templates.
First you would capture the entire URL in your urls.py file
original urls.py
...
(r'^myapp/$', 'myView'),
(r'^myapp/(?P<pk>.+)/$', 'myOtherView'),
...
new urls.py
...
(r'^(?P<whole_url>myapp/)$', 'myView'),
(r'^(?P<whole_url>myapp/(?P<pk>.+)/)$', 'myOtherView'),
...
Then in your view something like:
views.py
...
def myView(request, whole_url):
# dissect the url
slugs = whole_url.split('/')
# for each 'directory' in the url create a piece of bread
breadcrumbs = []
url = '/'
for slug in slugs:
if slug != '':
url = '%s%s/' % (url, slug)
breadcrumb = { 'slug':slug, 'url':url }
breadcrumbs.append(breadcrumb)
objects = {
'breadcrumbs': breadcrumbs,
}
return render_to_response('myTemplate.html', objects)
...
Which should be pulled out into a function that gets imported into the views that need it
Then in your template print out the breadcrumbs
myTemplate.html
...
<div class="breadcrumb-nav">
<ul>
{% for breadcrumb in breadcrumbs %}
<li>{{ breadcrumb.slug }}</li>
{% endfor %}
</ul>
</div>
...
One shortcoming of doing it this way is that as it stands you can only show the 'directory' part of the url as the link text. One fix for this off the top of my head (probably not a good one) would be to keep a dictionary in the file that defines the breadcrumb function.
Anyways that's one way you could accomplish breadcrumbs, cheers :)
You might want to try django-headcrumbs (don’t worry, they are not going to eat your brains).
It’s very lightweight and absolutely straightforward to use, all you have to do is annotate your views (because defining crumbs structure in templates sounds crazy to me) with a decorator that explains how to get back from the given view.
Here is an example from the documentation:
from headcrumbs.decorators import crumb
from headcrumbs.util import name_from_pk
#crumb('Staff') # This is the root crumb -- it doesn’t have a parent
def index(request):
# In our example you’ll fetch the list of divisions (from a database)
# and output it.
#crumb(name_from_pk(Division), parent=index)
def division(request, slug):
# Here you find all employees from the given division
# and list them.
There are also some utility functions (e.g. name_from_pk you can see in the example) that automagically generate nice names for your crumbs without you having to wright lots of code.
I've created template filter for this.
Apply your custom filter (I've named it 'makebreadcrumbs') to the request.path like this:
{% with request.resolver_match.namespace as name_space %}
{{ request.path|makebreadcrumbs:name_space|safe }}
{% endwith %}
We need to pass url namespace as an arg to our filter.
Also use safe filter, because our filter will be returning string that needs to be resolved as html content.
Custom filter should look like this:
#register.filter
def makebreadcrumbs(value, arg):
my_crumbs = []
crumbs = value.split('/')[1:-1] # slice domain and last empty value
for index, c in enumerate(crumbs):
if c == arg and len(crumbs) != 1:
# check it is a index of the app. example: /users/user/change_password - /users/ is the index.
link = '{}'.format(reverse(c+':index'), c)
else:
if index == len(crumbs)-1:
link = '<span>{}</span>'.format(c)
# the current bread crumb should not be a link.
else:
link = '{}'.format(reverse(arg+':' + c), c)
my_crumbs.append(link)
return ' > '.join(my_crumbs)
# return whole list of crumbs joined by the right arrow special character.
Important:
splited parts of the 'value' in our filter should be equal to the namespace in the urls.py, so the reverse method can be called.
Hope it helped.
A generic way, to collect all callable paths of the current url could be resolved by the following code snippet:
from django.urls import resolve, Resolver404
path_items = request.path.split("/")
path_items.pop(0)
path_tmp = ""
breadcrumb_config = OrderedDict()
for path_item in path_items:
path_tmp += "/" + path_item
try:
resolve(path_tmp)
breadcrumb_config[path_item] = {'is_representative': True, 'current_path': path_tmp}
except Resolver404:
breadcrumb_config[path_item] = {'is_representative': False, 'current_path': path_tmp}
If the resolve function can't get a real path from any urlpattern, the Resolver404 exception will be thrown. For those items we set the is_representative flag to false. The OrderedDict breadcrumb_config holds after that the breadcrumb items with there configuration.
For bootstrap 4 breadcrumb for example, you can do something like the following in your template:
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
{% for crumb, values in BREADCRUMB_CONFIG.items %}
<li class="breadcrumb-item {% if forloop.last or not values.is_representative %}active{% endif %}" {% if forloop.last %}aria-current="page"{% endif %}>
{% if values.is_representative %}
<a href="{{values.current_path}}">
{{crumb}}
</a>
{% else %}
{{crumb}}
{% endif %}
</li>
{% endfor %}
</ol>
</nav>
Only the links which won't raises a 404 are clickable.
I believe there is nothing simpler than that (django 3.2):
def list(request):
return render(request, 'list.html', {
'crumbs' : [
("Today", "https://www.python.org/"),
("Is", "https://www.python.org/"),
("Sunday", "https://www.djangoproject.com/"),
]
})
Breadcrumbs.html
<div class="page-title-right">
<ol class="breadcrumb m-0">
{% if crumbs %}
{% for c in crumbs %}
<li class="breadcrumb-item {{c.2}}">{{c.0}}</li>
{% endfor %}
{% endif %}
</ol>
</div>
css:
.m-0 {
margin: 0!important;
}
.breadcrumb {
display: flex;
flex-wrap: wrap;
padding: 0 0;
margin-bottom: 1rem;
list-style: none;
border-radius: .25rem;
}
dl, ol, ul {
margin-top: 0;
margin-bottom: 1rem;
}
ol, ul {
padding-left: 2rem;
}