I am using Django flatpages and would like to implement some logic in a template based on a user session variable.
eg.
{% if session.my_var %}
YES
{% else %}
NO
{% endif %}
Problem is that session object is not defined in flatpage context.
Create a TEMPLATE_CONTEXT_PROCESSOR which is then used by the RequestContext (see docs).
def session(request):
return { 'session': request.session }
Related
(Django , Python) I have created a list of book objects and it is being passed as context in my views.py along with the current session. On my template, i was to check if the books in that list are stored in the session, and if they are i want to access some info relating to that book within that session. how do i access the books in the session dynamically? is there a way?
i know i can access them by using "request.session.name" (where "name" is the same of the space in the session it is stored)
There are several book titles saved in the session, the way they are saved are as follows (in a function under views.py)
request.session["random book title"] = "random dollar price"
i want to access that "random dollar price" dynamically in a template.
this is the block of code in the template
{% for book in book_list %}
{% if book.title in request.session %}
{{ request.session.??? }}
{% endif %}
{% endfor %}
Thank you in advance!
You can make a custom template tag to look up by attribute like here
Performing a getattr() style lookup in a django template:
# app/templatetags/getattribute.py
import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
Now change your template to
{% load getattribute %}
{% for book in book_list %}
{% if book.title in request.session %}
{{ request.session|getattribute:book.title }}
{% endif %}
{% endfor %}
This is a basic custom template tag example:
Django - Simple custom template tag example
and docs:
https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/
From what I remember from my django days should work
You can put session data in a dictionary and send this data to target template when you want to render it in view function.
def some_function(request):
context={
'data':sessionData #put session data here
}
return render(request,"pass/to/template.html",context)
Now you can access 'data' in your template.html
I think you should just send a list of book names from your view instead of a queryset so when you are crosschecking with session you use the title directly instead.
{% for book in book_list %}
{% if book in request.session %}
{{ request.session.book }}
{% endif %}
{% endfor %}
I'm using Python with Flask and Jinja2 and I'm trying to implement a sidebar. In the HTML pages I have got this:
{% include "sidebar.html" %}
What I want in the sidebar file is to have a block of the latest users. To do that I need to get the results from the server for the sidebar.html file. But where should I write the code for that in the python file?
The way you could implement this functionality is by creating a Jinja variable on the python side:
app = Flask(__name__)
app.jinja_env.globals.update({
'latest_users': get_latest_users()
})
def get_latest_users() {
return ['Mark', 'Jane', 'Sally']
}
The variable latest_users can now be accessed from any Jinja template simply by doing:
{% for user in latest_users %}
<p>{{ user }}</p>
{% endfor %}
You can pass variables to the templates. When you use include your variables still can be used in this included part too:
#app.route('/')
def index():
users = ['user1', 'user2']
debug = False
render_template('index.html', users=users, debug=debug)
# index.html
{% include "sidebar.html" %}
#sidebar.html
{% for user in users %}
<p>{{ user }}</p>
{% endfor %}
{{debug}}
In django admin, we can define custom templates per app. In this case, I'm customising the app_index.html template for my application.
I'd like to add a few graphs and other to that page. Now that I've overridden the template, how can I override the corresponding view method?
I thought about making a custom AdminSite and override the app_index() (see https://github.com/django/django/blob/master/django/contrib/admin/sites.py#L511) method, but I have more than one application in my django installation, all of which will have a custom app_index.html.
What's the best way to add context to the app_index.html template?
Don't know if this is the best way, but it can be done with template
tags. Here is how I did it:
# <app>/templatetags/erp.py
register = template.Library()
#register.assignment_tag
def erp_get_tasks ():
return Task.objects.exclude (done=True).order_by ('priority')
.
# <app>/templates/admin/erp/app_index.html
{% extends "admin/app_index.html" %}
{% load erp %}
...
{% block footer %}
{% erp_get_tasks as tasks %}
{% for task in tasks %}
...
Is there a way to access the ADMINS variable of the settings module from an any arbitrary template without adding manually adding it into the context before being rendered, similar to how request is available in any template using RequestContext if django.core.context_processors.request is in TEMPLATE_CONTEXT_PROCESSORS?
You can write your own context processor (which is a regular function that has request as parameter):
from django.conf import settings
def admin_emails(request):
return { 'ADMINS': settings.ADMINS }
and add path.to.my.context_processor.admin_emails to TEMPLATE_CONTEXT_PROCESSORS.
I'd use a template tag like discussed for this question:
Can I access constants in settings.py from templates in Django?
Specifically I use the code from this answer: https://stackoverflow.com/a/6343321/2250326
With that you can get at the AMDINS in your templates like this:
{% value_from_settings "ADMINS" as admins %}
{% for admin in admins %}
Name: {{ admin.0 }}<br />
Email: {{ admin.1 }}
{% endfor %}
I have simple jinja2 template with registration/login links, I should hide them when user logged in, I also use flask_login module for this stuff.
Question is: How should I identify is user logged in in jinja2 templates?
Flask-Login adds the current_user variable to your templates:
{% if current_user.is_authenticated %}
...
{% else %}
...
{% endif %}
They mention this briefly in the documentation.