Use django-pagination to generate link refl=next/prev - django

I'm using django-pagination to paginate my pages. It works great, but I would like to set up
<link rel="prev" href="http://www.example.com/foo/?page=1" />
<link rel="next" href="http://www.example.com/foo/?page=3" />
to the <head>, like it is recommended by google .
However I found no way ho to do this (without extra queries at least). First I tried to edit the pagination/templates/pagination.html with something like this
{% block extra_head %}
<link rel=... ... />
{% endblock %}
Which of course did not work (pagination.html is included by the {% paginate %} tag, it does not extend my layout.html). Next, I tried to modify my template for /foo/ view to something like this (adding the {% block extra_head %}):
{# foo.html #}
{% extends "layout.html" %}
{% block content %}
{% load pagination_tags %}
{% autopaginate object_list %}
{% paginate %}
{% for obj in object_list %}
{{ obj }}
{% endfor %}
{% paginate %}
{% endblock %}
{% block extra_head %}
<link rel="prev" href="?page={{ page_obj.previous_page_number }}"/>
{% endblock %}
But this won't work either, as the page_obj variable is only available in scope of {% block content %}. A could call
{% autopaginate object_list %}
in the extra_head block, but that will mean an extra hit to the db (and possibly other side effects that I'm not aware of). Is there an elegant way to solve this, ideally as DRY as possible?
Edit: I'm using django 1.2.

You can do {% autopaginate %} in higher-level block, then paginated objects will be available in sub-blocks. If you don't have higher level block it is possible to do this in base template:
{% block root %}
...
{% endblock %}
And in extended template:
{% extends "base.html" %}
{% load pagination_tags %}
{% block root %}
{% autopaginate objects 10 %}
{{ block.super }}
{% endblock %}
<!-- the rest of your code -->
Now, to get a different rendering of paginator in head, you can make use of the with tag:
{% with we_are_in_head=1 %}
{% paginate %}
{% endwith %}
And override templates/pagination/pagination.html with something like this:
{% if we_are_in_head %}
# Your links to next and prev only
{% else %}
# original code
{% endif %}
A moral
This is not elegant and the reason is that pagination should be implemented in the view. Templates are for rendering only, template-tags too. Pagination makes extra sql queries, it also parses arguments from request, template is totally wrong place for this code, so workarounds has to be invented. These workarounds might break on next release of django, they are also subtle and can be accidentally broken by other developer.

We can call autopaginate in a view and then use {% paginate %} as usual. Here is a recipe if somebody still face the described problem:
from pagination.templatetags.pagination_tags import AutoPaginateNode
def autopaginate(request, context, queryset_var, paginate_by):
""" It allows us to use paginated objects in different template blocks """
autopagination = AutoPaginateNode(queryset_var, paginate_by)
# Inject a request - it's required by `autopagination` function
context['request'] = request
autopagination.render(context)

Related

Django: Frequent use of include template tag - how much is too much?

I noticed that I started using include template a lot. One of my template files has 20+ include tags.
Some of them are for modal dialogs that in turn have include for different form field sets. I am also using basically the same buttons with different data attributes so these are also done with include tags. Some my "fragments" that I use with include have around only five lines of HTML code.
I worry if this is too much and can negatively affect performance (since Django loads another files, etc..)
For example whis is markup of one of my HTML fragments I am using with include:
<div class="form-group">
<input type="url" class="form-control" id="video-link-input" name="video_link"
placeholder="YouTube link">
</div>
<input type="hidden" id="video_id" name="video_id" value="">
<img class="img-fluid img-thumbnail" id="video-img-preview">
Hope the question is not too broad. I would just like to avoid possible bad practice.
Overly fragmented templates will impact your performance, but not because Django loads files.
With the default settings, Django caches template files when DEBUG=False:
django.template.loaders.cached.Loader
...
This loader is automatically enabled if OPTIONS['loaders'] isn’t
specified and OPTIONS['debug'] is False (the latter option defaults to
the value of DEBUG).
IMHO, having lots of includes is not a bad practice in itself. The alternative would be repeating the code, which violates the DRY principle.
If you find yourself including the same template multiple times within one template, you might want to consider a custom inclusion tag.
If you are really worried about performance, look into caching and specifically template fragment caching.
According to Django documentation:
using {% block %} is faster than using {% include %}
heavily-fragmented templates, assembled from many small pieces, can
affect performance
You can use extends and block
Few examples:
In base.html I use these blocks
...
{% block navbar %}
{% endblock %}
{% block sidebar %}
{% endblock %}
{% block searchbar %}
{% endblock %}
{% block content %}
{% endblock %}
{% block footer %}
{% endblock %}
...
Now I extend base.html into login.html. Say my login.html just need navbar, content, and footer
{% extends 'base.html' %}
<h1>Login </h1>
{% block navbar %}
This is my navbar
{% endblock %}
{% block content %}
Here is my login form
{% endblock %}
{% block footer %}
This is footer
{% endblock %}
Now I extend base.html into home.html. Say my home.html need navbar, sidebar, searchbar, content, and footer
{% extends 'base.html' %}
<h1>Home page </h1>
{% block navbar %}
This is my navbar
{% endblock %}
{% block sidebar %}
This is sidebar
{% endblock %}
{% block searchbar %}
{% endblock %}
{% block content %}
This is homepage contents. This will not render which you use in login.html **content** block
{% endblock %}
{% block footer %}
{% endblock %}

Wagtail Index page not displaying objects of children

I am at my wits-end and feel I am missing something simple but I've looked at it over and over and can't figure it out.
I have a simple person_index_page that I want to show the child person_page objects, but no matter what I try...nothing. I have several sites with a similar setup and they work. Can you please look at my code below and see if you notice something I am missing? Thank you.
home_tags.py
# Person feed for home page and staff page
#register.inclusion_tag(
'home/tags/person_listing_homepage.html',
takes_context=True
)
def person_listing_homepage(context, count=3):
people = PersonPage.objects.live().order_by('?')
return {
'people': people[:count].select_related('feed_image'),
'request': context['request'],
}
person_index_page.html
{% extends 'base.html' %}
{% load wagtailcore_tags wagtailimages_tags home_tags %}
{% block content %}
...
{% include "home/tags/person_listing_homepage.html" %}
...
{% endblock %}
person_listing_homepage.html probably should name this at some point
{% for person in people %}
{% include "home/includes/person_list_item.html" %}
{% endfor %}
person_list_item.html
{% load wagtailcore_tags wagtailimages_tags %}
{# Individual person item in a list - used on people index and home page #}
<a class="list-group-item" href="{% pageurl person %}">
<div class="media">
{% if person.feed_image %}
<div class="media-left">
{% image person.feed_image width-200 as img %} <img class="media-object" src="{{ img.url }}"/>
</div>
{% endif %}
<div class="media-body">
<h4 class="media-heading">{{ person.first_name }} {{ person.last_name }}</h4>
{% if person.search_description %}
<p>{{ person.search_description }}</p>
{% endif %}
</div>
</div>
</a>
This is more of a "how to debug" question than a Wagtail one. Rather than just giving you the answer directly, here's the process I would take:
You say that adding print(people) inside the person_listing_homepage function doesn't display anything. So, your next question should be: "is this function being run at all?" Change the print statement to print("GOT HERE"). You'll find that this doesn't display anything either - which tells you that the function is not being run.
The next step would be to add some debugging output around the place where the function should be called from - if that doesn't get displayed either, you know that code isn't being run either, and you'd have to keep going up a level until you find something that is being run. So let's look for that place...
And this is where you find the problem. You never call the person_listing_homepage function anywhere in your code. You include the person_listing_homepage.html template, but that's not the same thing. person_index_page.html should become:
{% extends 'base.html' %}
{% load wagtailcore_tags wagtailimages_tags home_tags %}
{% block content %}
...
{% person_listing_homepage %}
...
{% endblock %}

How to extend a base.html using two different files?

I'm writing an application in which user can choose one of several tools for data analysis and open it in a panel on main page. Is it possible to use django "extends" and have each tool defined in different file?
The minimal example of what im strugling with would be like this:
base.html
<div>
{% block left_panel %}
left block
{% endblock content%}
</div>
<div>
{% block right_panel %}
right block
{% endblock %}
</div>
and sample left_panel and right_panel tools:
left1.html
{% extends "base.html" %}
{% block left_panel %}
<p>TEST left 1</p>
{% endblock %}
right1.html
{% extends "base.html" %}
{% block right_panel %}
<p>TEST right 1</p>
{% endblock %}
Is there a way to render the base.html with both blocks overwriten?
I believe that the best way to implement your requirement is to create a new template that extends base.html and includes left1.html and right1.html. Something like this:
{% extends "base.html" %}
{% block left_panel %}
{% include "left1.html" %}
{% endblock content%}
{% block right_panel %}
{% include "right1.html" %}
{% endblock %}
Update based on OP's comment: Actually you just need one configurable template, not 100. Let's say that based on the tools the user selects, your view passes the left_tool and right_tool context variables to your template. Now, you can easily do something like this:
{% block left_panel %}
{% if left_tool == "tool1" %}
{% include "left1.html" %}
{% elif left_tool == "tool2" %}}
{% include "left2.html" %}
etc ...
{% else %}
{% include "left10.html" %}
{% endif %}
{% endblock content%}
You'll do the same with the right panel. Of course the above is a little naive and definitely not DRY -- instead you could for instance generate the name of the template to be included in the view and pass it directly to the template, or use a custom node etc.

extend other app to my template working

I want to extend an other template to my blog.html, no matter have i try to extend this, it doesn`t work .
blog/index.html
{% block nav %}
<ul id="nav">
<li>{% block nav-blog %}Blog{% endblock %}</li>
<li>{% block nav-photo %}Photo{% endblock %}</li>
</ul>
{% endblock %}
<div class="news">
{% block polls %}
{% extends 'polls/index.html' %}
{% endblock %}
<div>
polls/index.html
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li>{{ poll.question }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Usually extends has to be stuck at the top of the template and not somewhere in the template.
In the template you use the tags that you have set up in the base templates.
You need to make sure you're doing two things here:
Declare a "nav" block in your index.html. This will let django know the part of your index html you wish to have overwritten when a template extends it. Anything you put inside the "nav" block in index html will be considered default content.
You need to use the "extends" template tag at the beginning of your blog.html so django knows the template you'd like to extend.
Like this:
index.html
{% block nav %}
<div>
Some default html here..
</div>
{% endblock %}
And then blog.html
{% extends index.html %}
{% block nav %}
<div>
This is what will render
</div>
{% endblock %}
Also, you're going to want to test index.html before trying to extend it to verify that django is finding that template. If it isn't then you need to add the directory that it is found in to the TEMPLATE_DIRS array in your settings.py file.

Django: with tag outside blocks

It seems like the 'with' tag is not working if it is declared outside of a block as this:
{% extends 'base.html' %}
{% with my_var=1 %}
{% block test1 %}
{{my_var}}
{% endblock %}
{% block test2 %}
{{my_var}}
{% endblock %}
{% endwith %}
The template above simply displays nothing since my_var is NOT passed inside those blocks.
How can I overcome this?
I came to Django from using Tornado with Jinja2 and I was being driven insane by the inability to set variables that (a) could be defined in the template (not view) and (b) would be available in the base template that this derives from. Looking at a little four-line piece of code from django-libs, I was able to rig up something like this that worked well. Here is an example of a title string that should appear in various blocks.
settings.py -- add to TEMPLATES (Django 1.10+)
TEMPLATES = {
...
builtins = ['mysite...wherever...templatetags',]
}
mysite.whereever.templatetags.py
from django import template
register = template.Library()
#register.simple_tag(takes_context=True)
def setvar(context, key, value):
context.dicts[0][key] = value
return ''
base.html
{% block settings %}
{% comment %}
Put this at the TOP of the template before
any blocks that use variables.
{% endcomment %}
{% endblock settings %}
<html>
<head><title>{{title}}</title></head>
<body><h1>My Site: {{title}}</h1>
{% block body %}
{% endblock body %}
</body></html>
menu.html -- a template that does not set 'title' in views:
{% extends "base.html" %}
{% block settings %}
{{ block.super }} {% comment %}optional{% endcomment %}
{% setvar 'title' 'Menu' %}
{% endblock %}
{% block body %}
<ul><li>Fish</li><li>Steak</li></ul>
{% endblock %}
Now the title will appear in two places in the HTML even though it is defined in the derived template but appears in the top template.