accessing serialised values in request.session - django

hopefully this is a rather simple question.
If i have the following stored in request.session. Assuming i have multiple items (only one shown here), I'd like to be able to loop over these items and render them as part of a template.
How can i access the quantity key and value for use within a for loop?
Here's what I'm trying, however there's no output.
{% for item in request.session.bookingContents.items %}
{{ item.quantity }}
{% endfor %}
Variable:
'bookingContents'
Value:
{u'cartID': 51,
u'items':
{u'1':
{
u'quantity': 25},
}
}
}
Further information (updated as this question evolves):
Active template context processors are:
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
#allauth specific template processors below
'allauth.account.context_processors.account',
'allauth.socialaccount.context_processors.socialaccount',
'django.contrib.messages.context_processors.messages',

You need to add django.core.context_processors.request to your template context processors.
Add this to your settings.py
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
TEMPLATE_CONTEXT_PROCESSORS = TCP + (
'django.core.context_processors.request',
)
Then you can access the session from your templates like this and your code should work:
{{ request.session.foo}}
UPDATE:
Ok your settings and view is fine, then you could try:
{% for key, value in request.session.bookingContents.items.items %}
{{ value.quantity }}
{% endfor %}

Related

How to display Model in each HTML template?

But create a request in each functions inside views.py I do not want.
Is it possible to output the model in each template using only one request?
I tried to use templateetags but
that so
#register.simple_tag(takes_context=True)
def header_categories(context):
return Categorie.objects.all().order_by('id')
what is like that
#register.simple_tag(takes_context=True)
def header_categories(context):
categories = Categorie.objects.all().order_by('id')
args = {}
for cat in categories:
args[cat.text] = {
'id':cat.id,
}
if cat.parent:
args[cat.text]['parent_id'] = cat.parent.id
args[cat.text]['parent_text'] = cat.parent.text
return args
Nothing works correctly
{% for cat in header_categories %}
cat.text
{% endfor %}
I tried through js
var arr = {%header_categories%}
but django changes everything
{'dresses': {'id': 19},
Before going deeper into your question, I think you should have
{% for cat in header_categories %}
{{ cat.text }}
{% endfor %}
You need to make a custom context processor (See Using RequestContext [Django docs]). What this would do is add a variable to the context for each template. Quoting the documentation:
The context_processors option is a list of callables – called
context processors – that take a request object as their argument and return a dictionary of items to be merged into the context.
In some suitable app of yours make a file named context_processors.py and add this code in it:
def header_categories(request):
return {'header_categories': Categorie.objects.all().order_by('id')}
Now in your settings in the TEMPLATES settings add this context processor to the list context_processors, so it should look like:
[
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'your_app.context_processors.header_categories',
]
Now in your templates you can simply write:
{% for cat in header_categories %}
{{ cat.text }}
{% endfor %}

Django: check for exact url in request using regex

I need to check if the url is exactly:
http://127.0.0.1:8000/shop/
and based on this render a header.
If it is, for example:
http://127.0.0.1:8000/shop/stickers/stickers-por-hoja/medida-y-cantidad
Header shouldn't render.
I've read you can do something like this:
{% if "/shop/$" in request.path %}
{% include 'header.html' %}
{% endif %}
But this doesn't work. On the other hand this works, but is not what I need:
{% if "/shop/" in request.path %}
{% include 'header.html' %}
{% endif %}
So, Can I use regex in the if condition?
Create a context processor has_shop_in_url.py having this code below.
import re
def has_shop(request):
shop_in_request = your_regex_validation
return {
'has_shop_in_url': any([shop_in_request]) }
Add that context processor
TEMPLATES = [
{
.....
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'your_module.has_shop_in_url.has_shop' # YOUR PROCESSOR
],
},
},
]
Now it is available for your whole web application. In template just write {{has_shop_in_url}}. Your can see True/False.
You could move the regex check into the view and add a field to the context for the template like so:
class MyView(View):
def action(self, request, *args, **kwargs):
shop_in_request = re.findall(r"/shop/$", request.path)
context = {"include_header": any(shop_in_request)}
return render(template, context)
Then in your view you could use:
{% if include_header %}
{% include 'header.html' %}
{% endif %}
Create a template tag to do that.
The url whitelisted must be somewhere in the settings. For example you can add something like this
HEADER_WHITELIST_URLS = (
'regex1',
'regex2',
)
2) Your template tags will check the current URL and if one of the regex matches, you can render your header. In a hypothetical version2, you can also add the header to show for a specific regex.
Use this snippet as starting point for your template tag
import datetime
from django import template
from django.conf import settings
register = template.Library()
#register.simple_tag(takes_context=True)
def render_header(context, format_string):
regexs = settings.HEADER_WHITELIST_URLS
# maybe you can add some try/exception if the settings is not available.
for regex in regexs:
# test the regex with the url in the context.
# if matches return the code to render the header and break
return None
Check here for more details about the template tags: https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/#writing-custom-template-tags

How do I call my dict parameters from the view.py render in my template?

I have been working on this for two day, and have read almost every example on stackoverflow and consulted the django documentation. I am trying to pass my dict from the views.py to my template, but I keep getting the stupid "Could not parse the remainder" error. I'm not doing anything fancy. Just Href buttons passing in a parameter to represent what that button is. Then a template page opens using that parameter as a string to make the new page and url unique.
pass in with:
Call
urls.py
urlpatterns = [
url(r'^call=(\d+)/$', views.call, name='call')
]
views.py
def call(request, callID):
call_id = { 'id':callID }
return render(request, 'site/call.html', call_id)
Call template
{% extends 'site/layout.html' %}
{% block content %}
{% with call_id.get('id') as view_id %}
<h3 class="center-align blue lighten-3">Site # Room {{ view_id }}</h3>
Cancel
{% endwith %}
{% endblock %}
I have tried request.GET.get('id') and a bizillion other things. Can someone show me how I can actually parse those dict values I passed in?
You're not actually passing a dictionary at all. You're passing a single value, id, so you should just use that. And there is no need for any with block.
Site # Room {{ id }}

Test the return value of a template tag

There's a boolean variable defined in settings.py that I'd like to make visible in my templates, so that I can control whether a part of the template is shown.
I've thought of creating a template tag to expose the value to the template:
#register.simple_tag
def show_something():
return settings.SHOW_SOMETHING
... which I would use in the template like this:
{% if show_something %}
Show it
{% endif %}
... but unfortunately it doesn't seem to work.
Also tried outputting the value, and this displays it as I expected:
{% show_something %}
Any idea if using a template tag is possible for what I need, or if there's a better way?
I think a template context processor might be better suited for this. Put a context_processors.py file in your project
context_processors.py
from django.conf import settings
def some_setting(request):
# Or some other logic here instead of always returning it
return {
'some_setting': settings.SOME_SETTING
}
settings.py
SOME_SETTING = False
TEMPLATE_CONTEXT_PROCESSORS = (
...,
'path.to.context_processors.some_setting'
)
and in your templates you can now access the variable with {{ some_setting }} or use it in an if statement like {% if some_setting %}Show this{% endif %}

How get current user in a template tag?

How can i get the current user in a django template tags? (request object is not accessible)
Or how can i access to request object?
If you want to access the current user in a template tag, you must pass it as a parameter in the templates, like so:
{% my_template_tag user %}
Then make sure your template tag accepts this extra parameter. Check out the documentation on this topic. You should also check out simple tags.
The user is always attached to the request, in your templates you can do the following:
{% if user.is_authenticated %}
{% endif %}
You don't have to specify "request" to access its content
UPDATE:
Be aware: is_authenticated() always return True for logged user (User objects), but returns False for AnonymousUser (guest users). Read here: https://docs.djangoproject.com/en/1.7/ref/contrib/auth/
This question was already answered here:
{% if user.is_authenticated %}
<p> Welcome '{{ user.username }}'</p>
{% else %}
Login
{% endif %}
and make sure you have the request template context processor installed in your settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.request',
...
)
Note:
Use request.user.get_username() in views & user.get_username in
templates. Preferred over referring username attribute directly.
Source
This template context variable is available if a RequestContext is used.
django.contrib.auth.context_processors.auth is enabled by default & contains the variable user
You do NOT need to enable django.core.context_processors.request template context processor.
Source : https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates
Suppose you have a profile page of every registered user, and you only want to show the edit link to the owner of the profile page (i.e., if the current user is accessing his/her profile page, the user can see the edit button, but the user can't see the edit button on other user's profile page.
In your html file:
<h2>Profile of {{ object.username }}</h2>
{% if object.username == user.username %}
Edit
{% endif %}
Then your urls.py file should contain:
from django.urls import path
from .views import ProfileUpdateView
urlpatterns = [
...
path('<int:pk>/profile/update', ProfileUpdateView.as_view(), name = 'profile_update'),
...
]
considering you have appropriate ProfileUpdateView and appropriate model