Creating Django Wagtail Sidebar with Index Page Child Links - django

I'm building a site using Django Wagtail and am having trouble figuring out how to add a sidebar menu that will list all the child pages of the parent index page. For example, I have a standard_index_page.html that I created a parent page with in Admin, then I added child pages of that using standard_page.html template.
In my standard_index_page.html template, I have the following code
{% standard_index_listing calling_page=self %}
and it displays all the child pages with links, but I would also like to display a list of all the child links on the child pages as well.
I hope this is making sense and someone can lend a hand. Thank you.

In essence you traverse the tree structure of your page hierarchy that is provided to Wagtail by Django-Treebeard.
Many front-end frameworks do not allow for multiple levels of menus as some consider it outside of best practices. However, with a library such as SmartMenus you can display this structure with a little elbow grease.
For my needs, there was no easy solution to this. So, while I want to share an example of how I went about this, it may be missing explanation. If you have any questions, I'd be happy to answer them.
I struggled with this for awhile and while there may be easier methods to traverse the tree, I built the following method as my needs expanded. It allows us to traverse all live pages in our site, check when the current page is being rendered in the menu, and allows for fine-grained control over rendering.
Here's what we're going to do:
Create a few template tags that will get the site root of the
current site, loop through direct children of the site root, and loop through any lower levels of children, while looping through children of the current menuitem when discovered at each level.
In your base template, this means we need to:
{% load demo_tags %} to import our custom template tags
Call {% top_menu calling_page=self %} to get and render all
direct children of the site root. These are items that would be shown across a standard menu bar.
Call {% top_menu_children parent=menuitem %} within the template
rendered by {% top_menu %} to get and render all second- and
lower-level children pages. This encompasses all menu items to be shown when hovering on the parents menu item.
Here's the custom demo_tags.py file I created to traverse all levels of the page hierarchy. The beauty of this is that it does not require any custom context data to be supplied; it works out of the box with Wagtail!
#register.assignment_tag(takes_context=True)
def get_site_root(context):
'''
Returns a core.Page, not the implementation-specific model used
so object-comparison to self will return false as objects would differ
'''
return context['request'].site.root_page
def has_menu_children(page):
'''
Returns boolean of whether children pages exist to the page supplied
'''
return page.get_children().live().in_menu().exists()
#register.inclusion_tag('info_site/tags/top_menu.html', takes_context=True)
def top_menu(context, parent, calling_page=None):
'''
Retrieves the top menu items - the immediate children of the parent page
The has_menu_children method is necessary in many cases. For example, a bootstrap menu requires
a dropdown class to be applied to a parent
'''
root = get_site_root(context)
try:
is_root_page = (root.id == calling_page.id)
except:
is_root_page = False
menuitems = parent.get_children().filter(
live=True,
show_in_menus=True
).order_by('title')
for menuitem in menuitems:
menuitem.show_dropdown = has_menu_children(menuitem)
return {
'calling_page': calling_page,
'menuitems': menuitems,
'is_root_page':is_root_page,
# required by the pageurl tag that we want to use within this template
'request': context['request'],
}
#register.inclusion_tag('my_site/tags/top_menu_children.html', takes_context=True)
def top_menu_children(context, parent, sub=False, level=0):
''' Retrieves the children of the top menu items for the drop downs '''
menuitems_children = parent.get_children().order_by('title')
menuitems_children = menuitems_children.live().in_menu()
for menuitem in menuitems_children:
menuitem.show_dropdown = has_menu_children(menuitem)
levelstr= "".join('a' for i in range(level)) # for indentation
level += 1
return {
'parent': parent,
'menuitems_children': menuitems_children,
'sub': sub,
'level':level,
'levelstr':levelstr,
# required by the pageurl tag that we want to use within this template
'request': context['request'],
}
In essence, there are three levels of pages rendered:
The site root is called by {% get_site_root %}
First-level children are called by {% top_menu %}
Second- and lower-level children are called by {% top_menu_children %}, which is called any time a page shown in the menu has children while rendering this tag.
In order to do this, we need to create the templates to be rendered by our top_menu and top_menu_children template tags.
Please note - these all are built for Bootstrap 3's navbar class and customized for my needs. Just customize these for your needs. The whole menu building process is called by {% top_menu_children %}, so place this tag in your base template where you want the menus rendered. Change top_menu.html to reflect the overall structure of the menu and how to render each menuitem. Change children_items.html to reflect how you want children of all top-menu items, at any depth, rendered.
my_site/tags/top_menu.html
{% load demo_tags wagtailcore_tags static %}
{% get_site_root as site_root %}
{# FOR TOP-LEVEL CHILDREN OF SITE ROOT; In a nav or sidebar, these are the menu items we'd generally show before hovering. #}
<div class="container">
<div class="collapse navbar-collapse" id="navbar-collapse-3">
<ul class="nav navbar-nav navbar-left">
{% for menuitem in menuitems %}
<li class="{% if menuitem.active %}active{% endif %}">
{% if menuitem.show_dropdown %}
<a href="{{ menuitem.url }}">{{ menuitem.title }}
<span class="hidden-lg hidden-md hidden-sm visible-xs-inline">
<span class="glyphicon glyphicon-chevron-right"></span>
</span>
</a>
{% top_menu_children parent=menuitem %}
{% else %}
{{ menuitem.title }}
{% endif %}
</li>
{% endfor %}
</ul>
</div>
</div>
my_site/tags/children_items.html
{% load demo_tags wagtailcore_tags %}
{# For second- and lower-level decendents of site root; These are items not shown prior to hovering on their parent menuitem, hence the separate templates (and template tags) #}
<ul class="dropdown-menu">
{% for child in menuitems_children %}
{% if child.show_dropdown %}
<li>
<a href="{% pageurl child %}">
{% for i in levelstr %}&nbsp&nbsp{% endfor %}
{{ child.title }}
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
{# On the next line, we're calling the same template tag we're rendering. We only do this when there are child pages of the menu item being rendered. #}
{% top_menu_children parent=child sub=True level=level %}
{# ^^^^ SmartMenus is made to render menus with as many levels as we like. Bootstrap considers this outside of best practices and, with version 3, has deprecated the ability to do so. Best practices are made to be broken, right :] #}
</li>
{% else %}
<li>
<a href="{% pageurl child %}">
<!-- Allows for indentation based on depth of page in the site structure -->
{% for i in levelstr %}&nbsp&nbsp{% endfor %}
{{ child.title }}
</a>
</li>
{% endif %}
{% endfor %}
</ul>
Now, in your base level template (let's assume you are using one; if not, get to it :) ) you can traverse the menu while keeping clutter cleared away to the templates used by your inclusion_tags.
my_site/base.html
<ul class="nav navbar-nav navbar-left">
{% for menuitem in menuitems %}
<li class="{% if menuitem.active %}active{% endif %}">
{% if menuitem.show_dropdown %}
<a href="{{ menuitem.url }}">{{ menuitem.title }}
<span class="hidden-lg hidden-md hidden-sm visible-xs-inline">
<span class="glyphicon glyphicon-chevron-right"></span>
</span>
</a>
{% top_menu_children parent=menuitem %}
{% else %}
{{ menuitem.title }}
{% endif %}
</li>
{% endfor %}
</ul>
I wrote a blog post about this - check it out for more details. Or, head over to Thermaline.com to see it in action, though I think there's not multiple levels of depth right now. IF THERE WERE, they'd be rendered automatically :)
Now, this example is for a navbar, but it could easily be adapted for a sidebar.
All you need to do is:
Include demo_tags in your base template
Call {% top_menu %} where you wish to render your menus.
Customize top_menu.html and children_items.html to render the
first and then all subsequent levels of pages.
Shout out to Tivix for their post on two-level menus that was a great starting point for me!

Related

How to display {% django block %} dynamically with for loop?

Hello Awesome People!
I'm building a dashboard for my website, in the left section, I have a menu containing multiple items : Home, Messenger, Job Offers ....
When creating an account, Users are able to choose their items, re-order or remove.
I have Menu & Item models,
class Menu(models.Model):
items = models.ManyToManyField('Item',blank=True)
class Item(models.Model):
name = models.CharField(max_length=100)
unique_key = models.CharField(max_length=100,unique=True)
url = ......
For the menu of the user, in my base_template I display the items of the current users with for loop. With a CSS class I want to highlight the current view, the current item.
When the user visits his messenger, I want to highlight that item messenger with a CSS class.
<ul>
{% for item in user.menu.items.all %}
<li class='{% block item.unique_key %}{% endblock %}'>
{{item.name}}
</li>
{% endfor %}
</ul>
Now, when being in messenger.html for example, knowing that I have a unique_key for messenger called item_messenger, I do
{% block 'item_messenger' %}active{% endfor%}
It's not working, the item Messenger or whatever I choose doesn't become highlighted, I wonder why?
Is there another way to achieve that?
Any hint will be helpful, thanks in advance!
You are trying to have the block tag interpret a variable as it's name. That doesn't work.
You will need to pass along the active item's key in the template context and then in your base_template you can just do a simple if statement to add the active class to the correct entry.
<ul>
{% for item in user.menu.items.all %}
<li class='{% if item.unique_key == active_key %}active{% endif %}'>
{{item.name}}
</li>
{% endfor %}
</ul>

Custom Template Tag Queryset Not Returning Anything

I'm trying to implement a feature that displays the 5 most recently created events. I decided to implement this with Django custom template tags (if this is not the best way, let me know). What I have so far is:
In event_search.html (among other things):
{% extends 'base.html' %}
{% load eventSearch_extras %}
<p>count: {{ recents.count }}</p>
<ul>
{% for e in recents %}
<li> {{e.title}} </li>
{% empty %}
<li> No recent events </li>
{% endfor %}
</ul>
In eventSearch_extra.py:
from django import template
from eventSearch.models import Event
register = template.Library()
#register.inclusion_tag('eventSearch/event_search.html')
def mostrecentevents():
"""Returns most 5 most recent events"""
recents = Event.objects.order_by('-created_time')[:5]
return {'recents': recents}
My issue here is that the queryset 'recents' appears to return empty to the template. 'count:' shows nothing & the for-loop defaults to 'No recent events'.
You've loaded the inclusion tag function, but not the individual tag, so the code to populate that information is never called; it's also laid out slightly oddly, so you're calling from the wrong place.
The main template calls the inclusion tag by using:
{% load eventSearch_extras %}
And you include the actual tag by calling
{{mostrecentevents}}
mostrecentevents goes off and runs the code, parses the html of event_search.html and puts it in the main template. The way your code is set out just now, you'd be calling an inclusion tag from its own HTML.
Main template > {% load inclusion_tags %} {{ actual_tag }}
As an example, I have a restaurant template. In that template is this code:
{% load restaurant_menu %} <!--main inclusion tag .py file) -->
{% menu %} <!-- the actual tag code you want to run -->
in restaurant_menu.py I have the following (additional irrelevant stuff removed):
#register.inclusion_tag('core/_menu.html', takes_context=True)
def menu(context):
filtered = context['filtered']
from core.models import MenuItem, FoodProfile, Ingredient, Recipe
if filtered:
restaurant = context['restaurant'].id
filtered_menu = #stuff here
restaurant_menu = filtered_menu
else:
restaurant_menu = MenuItem.objects.filter(restaurant__pk=context['restaurant'].id)
return {"restaurant_menu": restaurant_menu,
"number_of_menu_items": restaurant_menu.count(),
"filtered": filtered}
and the _menu.html page (underscored so I know it's a fragment) :
<ul>
{% for item in course.list %}
<li>
{{ item.number|floatformat:0 }} {{ item.name }} {{ item.description }} {{ item.price }} </li>
</li>{% endfor %}
{% endfor %}
</ul>
An inclusion tag is used to render another template. It doesn't make sense to create an inclusion tag that renders event_search.html, then call that template tag inside event_search.html itself. Note that you haven't actually used the template tag (with {% mostrecentevents %}), all you have done is load the template tag library.
It would be easier to use a simple tag instead.
#register.simple_tag
def mostrecentevents():
"""Returns most 5 most recent events"""
recents = Event.objects.order_by('-created_time')[:5]
return recents
Then in your template you can do:
{% load eventSearch_extras %}
{% mostrecentevents as recents %}
This loads the result of the template tag into the variable recents, and you can now do:
<p>count: {{ recents.count }}</p>
<ul>
{% for e in recents %}
<li> {{e.title}} </li>
{% empty %}
<li> No recent events </li>
{% endfor %}
</ul>
Note you can only use the as recents syntax with simple tags with Django 1.9+. For earlier versions, you can use an assignment tag instead.

Bootstrap navbar inconsistent height when logged in Django

Using the default Jumbotron theme with Django in PTVS, when logged in, all of the templates that I create have more height in the navbar. The text doesn't change, just the bottom margin of the navbar is further down by a few pixels.
The problem doesn't exhibit when:
The window is shrunk so the navbar shows the hamburger logo
I copy the exact code from my templates to overwrite a default template without changing the view
{% include 'app/loginpartial.html' %} is removed from layout.html
{% if user.is_authenticated %} is removed from loginpartial.html
I browse the problematic pages while logged out
I tried copying the view code from a default, but that didn't fix the problem. Any idea what/where is the problem, and how can it be fixed? Thank you!
Update Here's the code within loginpartial.html causing the problem, it seems to only affect pages that I've created and not the default pages:
<ul class="nav navbar-nav navbar-right">
<li><span class="navbar-brand">{{ user.username }}</span></li>
<li>Log off</li>
</ul>
views.py old
def places(request):
places = Place.objects.all()
return render(request, 'app/places.html', {'title':'Places','places':places,'year':datetime.now().year})
views.py attempted unsuccessful fix
def places(request):
assert isinstance(request, HttpRequest)
return render(
request,
'app/places.html',
context_instance = RequestContext(request,
{
'title':'Places',
'places':places,
'year':datetime.now().year,
})
)
loginpartial.html unchanged from default afaik
{% if user.is_authenticated %}
<form id="logoutForm" action="/logout" method="post" class="navbar-right">
{% csrf_token %}
<ul class="nav navbar-nav navbar-right">
<li><span class="navbar-brand">{{ user.username }}</span></li>
<li>Log off</li>
</ul>
</form>
{% else %}
<ul class="nav navbar-nav navbar-right">
<li>Log in</li>
</ul>
{% endif %}
Looks like you get the problem because of the next two things:
navbar-right class used twice in user.is_authenticated block. This class is used to set the position of navbar. To make other elements float right you should use pull-right class. So, try to delete this class from the form.
Moreover, why is <ul> wrapped with the form? Form is just a part of your navbar, so it should be inside the navbar. I'd recommend to use a <div> as a navbar holder in your case and to place <ul> and <form> (if you need it) inside it.

Expand pagination beyond previous, current, and next page (Django)

I'm using Pagination in my Django project and it all works properly, but I don't know how to expand my reach beyond +/- one page of the one I'm on. Currently, my html looks as such:
<div class="pagination pagination-centered">
<ul>
{% if title.has_previous %}
<li>«</li>
<li>{{ title.previous_page_number }}</li>
{% endif %}
<li class="active">{{ title.number }}</li>
{% if title.has_next %}
<li>{{ title.next_page_number }}</li>
<li>»</li>
{% endif %}
</ul>
</div>
This results in something that looks like [<<, 1, 2, 3, >>] if you are on page two. I'd like to expand the reach by maybe one or two steps or so. So if I'm on page 3, I can reach all the way from 1-5.
{# Create A Button Group that contains possible pages to navigate to #}
{% for page in paginator.page_range %}
{% if page < toolbar_max and page > toolbar_min and page != results.number %}
<button formaction="{% url 'volume:page' page=page %}">{{ page }}</button>
{% elif page == results.number %}
<button type="submit" formaction="{% url 'volumes:page' page=page %}">{{ page }}</button>
{% endif %}
{% endfor %}
Basically, you keep the minimum and maximum number page you want (toolbar_min and toolbar_max and pass that to your page.
# Variables to be passed for page menu
toolbar_max = results.number + 4
toolbar_min = results.number -4
So it will display 4 on each side of the number you are currently on. The 'results' is a query of mine that displays the current page I am on. I wanted that page to be highlighted with a different css class, and for it to know that it should be counting off of variable.

Factorizing a header menu in Django template

I'm building a website using django with a header on top of every page, which basically is a menu with a few links, constant throughout the pages.
However, depending on the page you're on I'd like to highlight the corresponding link on the menu by adding the class "active". To do so, I am currently doing as follow: each page has a full menu block that integrates within a general layout, which does NOT contain the menu. For exemple, page2 would look like this:
{% extends "layout.html" %}
{% block menu %}
<li>Home</li>
<li>page1</li>
<li class="active">page2</li>
<li>page3</li>
{% endblock %}
The problem is that, beside from that solution being not so pretty, every time I want to add a link to the header menu I have to modify each and every page I have. Since this is far from optimal, I was wondering if any of you would know about a better way of doing so.
Thanks in advance!
You can create a custom templatetag:
from django import template
from django.core.urlresolvers import reverse, NoReverseMatch, resolve
register = template.Library()
#register.simple_tag
def active(request, view_name):
url = resolve(request.path)
if url.view_name == view_name:
return 'active'
try:
uri = reverse(view_name)
except NoReverseMatch:
uri = view_name
if request.path.startswith(uri):
return 'active'
return ''
And use it in the template to recognize which page is loaded by URL
<li class="{% active request 'car_edit' %}">Edit</li>
If you have a "page" object at every view, you could compare a navigation item's slug to the object's slug
navigation.html
<ul>
{% for page in navigation %}
<li{% ifequal object.slug page.slug %} class="active"{% endifequal %}>
{{ page.title }}
</li>
{% endfor %}
</ul>
base.html
<html>
<head />
<body>
{% include "navigation.html" %}
{% block content %}
Welcome Earthling.
{% endblock %}
</body>
</html>
page.html
{% extends "base.html" %}
{% block content %}
{{ object }}
{% endblock %}
Where navigation is perhaps a context_processor variable holding all the pages, and object is the current PageDetailView object variable
Disclaimer
There are many solutions for your problem as noted by Paulo. Of course this solution assumes that every view holds a page object, a concept usually implemented by a CMS. If you have views that do not derive from the Page app you would have to inject page pretenders within the navigation (atleast holding a get_absolute_url and title attribute).
This might be a very nice learning experience, but you'll probably save loads time installing feinCMS or django-cms which both define an ApplicationContent principle also.
You may use the include tag and pass it a value which is the current page.
For example, this may be a separate file for declaring the menu template only:
menu.html
{% if active = "a" %}
<li>Home</li>
{% if active = "b" %}
<li>page1</li>
{% if active = "c" %}
<li class="active">page2</li>
{% if active = "d" %}
<li>page3</li>
And call this from within your template like this:
{% include 'path/to/menu.html' with active="b"%} # or a or c or d.
Hope it helps!