This question already has answers here:
How to access session variables in jinja 2 - Flask
(3 answers)
Pass variables to all Jinja2 templates with Flask
(2 answers)
Global variables in Flask templates
(1 answer)
What happens when you assign the value of one variable to another variable in Python?
(10 answers)
In Jinja2, how do you test if a variable is undefined?
(9 answers)
Closed 3 years ago.
I want to show different header for person with logged in and person who logged out in Flask. Could I use the session variable directly in the jija2 template.
I have used different name for session since , another session variable name used for sqlalchamy session.
from flask import session as usersession
I have tried accessing the usersession variable but it's saying undefined. but when I use the session['username'] I could access the session variable.
further when I pop from usersession It's not popping from the session. Still session accessed in the tamplete has the username variable
usersession.pop('email', None)
usersession.pop('type', None)
jinja2.exceptions.UndefinedError: 'usersession' is undefined
My code is below .
{% if usersession['username'] is not none %}
{% include "store/headers/loginheader.html" %}
{% else %}
{% include "store/headers/logoutheader.html" %}
{% endif %}
In your views function, try usersession[‘username’] = ‘username
And in the template:
{{ usersession[‘username’] }}
For sessions make sure you have set up the environment correctly to be able to access sessions (ie a secret key).
Also have a look at flask-login as their ‘current_user’ object has great functionality and may be what you’re looking for
Related
This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
i am relatively new to Flask/Python/HTML so please excuse my language.
Basically I am trying to retrieve the "name" field with request.form.get that was inputted in my HTML page. The name field was generated with a for loop in jinja. When i hit the checkbox, and click submit, i expect the request.form.get to retrieve the "name" field that was in that specific check boxes' data. However, when i test out the data, I get a 404 error that says NONE for the request.form.get value. I'm not sure where I am going wrong. I suspect it might be what I am plugging in as the name for request.form.get.
On my flask side:
#app.route("/recipedata", methods=["GET","POST"])
def recipedata():
if request.method == 'POST':
food = request.form.get("{{value.id}}")
On HTML side:
{% for value in foodinfo.results %}
<form action="/recipedata" method = "POST">
<input type="checkbox" name="{{value.id}}" value={{value.id}}>
<input type=text placeholder="{{value.id}}">
<input type="submit"> Go to Recipe info
</form>
{% endfor %}
The 2nd line in my form tag with type text was used to test whether my value.id was printing correctly in Jinja, and indeed it was. Additionally, for clarification, foodinfo is passed as a .json() object with nested dictionary key/values. Value.id allows me to access that dict's value at key 'id', I believe.
Thank you!
I don't think your function definition of recipedata() is valid as per python syntax. You need to indent code in python to preserve scope information. You can see more here.
Try with following function definition.
def recipedata():
if request.method == 'POST':
food = request.form.get("{{value.id}}")
I'm not sure if HTML part is causing any trouble.
i am writing a django views as shown:-
def feed(request):
if request.user.is_authenticated:
user=request.user
profile=Profile.objects.filter(user=user)
userfollowing=FollowingProfiles.objects.filter(Profile=profile)
for following in userfollowing:
username=following.ProfileName
useraccount=User.objects.filter(username=username)
Profile=Profile.objects.filter(user=useraccount)
Post=post.objects.filter(Profile=Profile)
comment=comment.objects.filter(post=Post)
final_post_queryset=final_post_queryset+Post
final_comment_queryset=final_comment_queryset+comment
return render(request,'feed/feed.html',{'final_comment_queryset':final_comment_queryset,'final_post_queryset':final_post_queryset})
else:
redirect('signup')
while template feed.html is:-
{% extends 'base.html' %}
{% block content %}
{% load static %}
{% for p in final_post_queryset %}
{{ p.DatePosted }}
<img src="{{ p.Picture.url }}"/>
{% endblock %}
while the error is:-
so the error is in the 3rd line of view
profile=Profile.objects.filter(user=user)
I'm assuming you already imported the Profile module (with from .models import Profile or the like), and are confused as to why it doesn't exist (if you haven't, you need to add that import to the top of your file).
Even if you have imported it, this code won't work. Your problem is you assigned to the name Profile at function scope, making it a local variable, and local variables are local (but initially empty) from the beginning of the function. Trying to access them before they're assigned to raises the UnboundLocalError you're seeing (that error is only raised when you try to read from a local name before you've assigned to it; it can't be raised simply by failing to import a module, which would simply raise a NameError). You couldn't see the globally imported Profile even if you did import it, because within the function, Profile must be local or global, it can't be both.
To fix, choose a different name for your local variable so the global Profile remains accessible:
def feed(request):
if request.user.is_authenticated:
user=request.user
profile=Profile.objects.filter(user=user) # This line is fine!
userfollowing=FollowingProfiles.objects.filter(Profile=profile)
for following in userfollowing:
username=following.ProfileName
useraccount=User.objects.filter(username=username)
# Use lowercase profile, not Profile
# Profile=Profile.objects.filter(user=useraccount) # This line was the problem!
profile = Profile.objects.filter(user=useraccount) # This line is the solution!
Post = post.objects.filter(Profile=profile) # Change to match new name
... rest of your code ...
You were already using lowercase profile correctly earlier, and never seem to need it again, so I just reused the name.
This question already has an answer here:
Reference template variable within Jinja expression
(1 answer)
Closed 7 years ago.
I need to pass dynamic values to my python view. My HTML looks like:
<a href="{{ url_for('refresh_page',
lang_code=g.current_lang,
feature='a+z+',
cata={{ att.get('url_slug')}})}}"
>
I need to pass this {{ att.get('url_slug')}} to my Flask View:
#app.route('/<lang_code>/category/<string:feature>/<string:cat>/<int:pag e>')
def navigate_page(feature, page):
But its not working. I just started working on views, what I am doing wrong. Please help!!
The url_for is already a template function, so no need to escape the parameter:
<a href="{{ url_for('refresh_page',
lang_code=g.current_lang,
feature='a+z+',
cata=att.get('url_slug')) }}">
This question already has an answer here:
Django - How to make a variable available to all templates?
(1 answer)
Closed 6 years ago.
I am trying to pass variables (browser variable) to all my templates in my app. Any advice on how to get it to work?
View:
def browser(request):
primary_cat_list = Categories.objects.order_by("category")
subcat_list = SubCategories.objects.order_by("sub_category")
product = Productbackup.objects.order_by("website")
browser = list(chain(primary_cat_list, subcat_list, product))
return render_to_response('reserve/templates/base.html', locals(), context_instance=RequestContext(request))
Template:
{% for prod in browser %} {{ prod }}, {% endfor %}
You, my friend, are in the market for Context Processors.
From a blog entry written by a far nimbler and erudite technical writer than I:
What are template context processors?
Django’s context processors are a facility that allows you to provide data and callbacks to your templates.
You can do so in one of two ways:
On an individual request basis: by passing a custom Context value to your render_to_response() call
Globally: by creating a context processor method that accepts a HttpRequest object as input, and returns a payload or callback, then
registering the context processor in your settings.py, then providing your render_to_response() call with the built-in RequestContext attribute
instead of your own (you can always extend RequestContext to add more data on an individual request basis of course).
If that approach for passing data to templates sounded absurd and obfuscated to you, you’re not alone. The complexity involved in such a simple operation is unwarranted and counter-productive, but every system has its shortcomings.
The official documentation is here:
https://docs.djangoproject.com/en/dev/ref/templates/api/
So but yeah, I have been programming with Django for a while, and one of the reasons I really like solving problems w/ it is because it is almost Byzantine in its complexity, but not in a domineering sort of way. It has a ton of geegaws and doodads that may not immediately appear useful; each of these either comes in extremely handy when you need it, and it will stay out of your way if not.
The upshot here for you is: context processors are a fine example of those. Yes.
Currently you're passing locals() as the variable scope which should include browser aswell, but I find the use of locals() very ugly.
Personally I always prefer a pattern like this instead:
def browser(request):
context = RequestContext(request)
primary_cat_list = Categories.objects.order_by("category")
subcat_list = SubCategories.objects.order_by("sub_category")
product = Productbackup.objects.order_by("website")
browser = list(chain(primary_cat_list, subcat_list, product))
context['browser'] = browser
return render_to_response('reserve/templates/base.html', context_instance=context)
I can give you an example of my code, that works fine. Here is the file named context_processors.py:
context_processors.py
def base(request):
user = request.user
#======================
#Login form
#=====================
# here is the code for login user or check if he is logged in already
return {
'user': user,
}
and that's, part of my base.html (a template that I use wor all my pages)
base.html
{% if user.username %}
<h3>
Welcome {{ user.username }}
</h3>
I want to add a context variable in Django, so that I could define its value on per-application basis, or leave it empty.
Example:
apps/someapp/views.py:
def_context_var('app_name', 'Calendar')
templates/base.html:
{% if app_name %}You are in {{ app_name }} app.{% endif %}
....
{% if app_name %}Subsections of {{ app_name }}: ...{% endif %}
I considered the following:
Declare a variable in the app (in a view, or in URLs), and make a context processor. But I can't understang how to extract that var given the request object.
Put decorators on views. Hm, I don't like the idea: too much boilerplate or duplicated code.
#1 but nicer: make methods (like in the example above) that are executed on server restart, write the data into a dict, then a context processor somehow (how?) gets the application name and extracts the data from the dict. Where do I put the method, the dict, how does the context processor know where the view object is in?
You can call resolve(request.path) in a context processor to resolve the current url. See the django documentation on resolve for its return values, especially app_name.