“{% extends %}” vs “{% include %}” in Django Templates

Extending allows you to replace blocks (e.g. “content”) from a parent template instead of including parts to build the page (e.g. “header” and “footer”). This allows you to have a single template containing your complete layout and you only “insert” the content of the other template by replacing a block. If the user profile is … Read more

How to get URL of current page, including parameters, in a template?

Write a custom context processor. e.g. def get_current_path(request): return { ‘current_path’: request.get_full_path() } add a path to that function in your TEMPLATE_CONTEXT_PROCESSORS settings variable, and use it in your template like so: {{ current_path }} If you want to have the full request object in every request, you can use the built-in django.core.context_processors.request context processor, … Read more

Access request in django custom template tags

request is not a variable in that scope. You will have to get it from the context first. Pass takes_context to the decorator and add context to the tag arguments. Like this: @register.inclusion_tag(‘new/userinfo.html’, takes_context=True) def address(context): request = context[‘request’] address = request.session[‘address’] return {‘address’:address}

How do I display the value of a Django form field in a template?

This was a feature request that got fixed in Django 1.3. Here’s the bug: https://code.djangoproject.com/ticket/10427 Basically, if you’re running something after 1.3, in Django templates you can do: {{ form.field.value|default_if_none:”” }} Or in Jinja2: {{ form.field.value()|default(“”) }} Note that field.value() is a method, but in Django templates ()‘s are omitted, while in Jinja2 method calls … Read more

How do you insert a template into another template?

You can do: <div class=”basic”> {% include “main/includes/subtemplate.html” %} </div> where subtemplate.html is another Django template. In this subtemplate.html you can put the HTML that would be obtained with Ajax. You can also include the template multiple times: <div class=”basic”> {% for item in items %} {% include “main/includes/subtemplate.html” %} {% endfor %} </div>