Django 1.6 messages not showing up - django

I followed the docs to import necessary stuff into my settings, views and template. However, no messaging is showing up.
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
Example view:
from django.contrib import messages
def add_news(request):
if request.method == 'POST':
form = NewsForm(request.POST)
if form.is_valid():
form.save()
messages.info(request, "News was added")
return HttpResponseRedirect('/')
if request.method == 'GET':
form = NewsForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('news/add_news.html', args)
In base.html I have:
{% block messages %}
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endblock messages %}
How should I debug this?

The messaging framework makes use of a context_processor to deliver the messages to the template. To make sure the variables from your context_processors are actually added to the context you render your template with, you have to use a RequestContext in your view.
If you’re using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context.
You are using the render_to_response method which doesn't do this by default. You either need to specify the use of a RequestContext or use the render function instead which does this by default
return render_to_response('news/add_news.html',
args,
context_instance=RequestContext(request))

Related

datepicker Is not showing?

I am developing an application with Django and I need to choose date and time. I am trying to do it with 'bootstrap_datepicker_plus', but the calendar does not appear when I show the form.
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hungryFalconryApp',
'rest_framework',
'bootstrap4',
'bootstrap_datepicker_plus',
]
BOOTSTRAP4 = {
'include_jquery': True,
}
forms.py
from django import forms
from bootstrap_datepicker_plus import DateTimePickerInput
class DateForm(forms.ModelForm):
class Meta:
model = Comedero
fields = ('dias', 'horas')
widgets = {
'dias': DateTimePickerInput(),
'horas': DateTimePickerInput(),
}
views.py
def programar_comederos(request, nombre):
if request.method == "POST":
form = DateForm(request.POST)
print(nombre)
if(form.is_valid()):
comedero = form.save(commit=False)
print(comedero.dias)
print(comedero.horas)
else:
form = DateForm()
return render(request, 'hungryFalconryApp/programar_comederos.html',{'nombre': nombre, 'form':form})
template.html
{% load bootstrap4 %}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
{% bootstrap_messages %}
{{ form.media }}
{% block content %}
<form action="" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% bootstrap_button "Guardar" button_type="submit" button_class="btn-primary" %}
</form>
{% endblock %}
I have already solved. In django-bootstrap-datepicker-plus it indicates putting {{form.media}} after this code but {{form.media}} must go inside the tag
you can also use Datepicker too, Datepicker is jqueryUI, its faster and also reliable
see example here
you just cdn or jqueryUI file in your project
jqueryUI CDN
<script
src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"
integrity="sha256-0YPKAwZP7Mp3ALMRVB2i8GXeEndvCq3eSl/WsAl1Ryk="
crossorigin="anonymous"></script>
then assign Id to that particular field
<script>
$("#datepicker").datepicker({ dateFormat: 'dd M yy' });
</script>
" datepicker " is html id you also change date format from dateFormat

templatetag: QuerySet' object has no attribute 'getlist'

I'm greeted with the following error when attempting to follow a books example of templatetags with modification:
QuerySet' object has no attribute 'getlist'report_id=88&report_id=89 HTTP/1.1" 500 180158
I'm following the instructions of adding templatetags to my app directory and included the init.py and the app_filter.py i'd like to filter on, as such:
Security
accounts
templatetags
app_filters.py
__init__.py
My app_filter.py is defined as such:
from django import template
register = template.Library()
#register.filter
def get_list(querydict, itemToGet ):
return querydict.getlist(itemToGet)
My settings.py includes the following:
INSTALLED_APPS = [
'django_python3_ldap',
'django_extensions',
'django_filters',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
]
My view is passing the array correctly:
checked = request.GET.get('report_id')
checkedlist = request.GET.getlist('report_id')
reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)
print (checked)
print (checkedlist)
args = {'retreivecheckbox': reportlist}
return render(request,'accounts/requestaccess.html', args)
I see the array in my console, when doing a print checkedlist:
['75', '76', '77']
My template is the following:
{% load app_filters %}
{% for reports in retreivecheckbox %}
{{ retreivecheckbox|get_list:'report_id' }}
</div>
{% endfor %}
You're calling #register.filter with a path. I think you mean to call it with #register.filter('get_list')
Take a look at the docs: these are the two use examples:
#register.filter(name='cut')
def cut(value, arg):
return value.replace(arg, '')
#register.filter
def lower(value):
return value.lower()
Those would create two filters, lower and cut.
Alternatively, you can call #register.filter and pass the name as the first parameter, as in these cases:
register.filter('cut', cut)
register.filter('lower', lower)
I had to use {{ retreivecheckbox|get_list:report_id }}
and not {{ retreivecheckbox|get_list:'report_id' }}
{% load app_filters %}
{% for reports in retreivecheckbox %}
{{ retreivecheckbox|get_list:report_name_sc }}
</div>
{% endfor %}

Django 1.4 messages framework

development server use django1.3 but deployment server is powered by django1.4. Messages framework won't work at all on the django1.4 but works great on 1.3 with following code.
settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
... ,
)
views.py
from django.contrib import messages
from django.http import HttpResponseRedirect
...
def some_view(request):
...
mess1 = 'Thank you! Your message was received.'
messages.info(request, mess1)
return HttpResponseRedirect('/contact/')
template
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %}
Have you added the messages template context processor?
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.messages.context_processors.messages",
)
See this for more info.

Issues with Django and pytz

I've followed the time zone documentation on the Django site with no luck. My issue is that I have a select box on my template that should be populated with common timezones provided by pytz, but, for whatever reason it's empty.
My end goal is to allow users to select their own time zone.
Any help is appreciated, thanks in advance.
view.py:
def set_timezone(request):
if request.method == 'POST':
request.session['django_timezone'] = pytz.timezone(request.POST['timezone'])
return redirect('/')
else:
return render(request, 'n2w/leads.html', {'timezones': pytz.common_timezones})
leads.html:
{% load tz %}
{{ datetime }}
<form action="" method="POST">
{% csrf_token %}
<label for="timezone">Time zone:</label>
<select name="timezone">
{% for tz in timezones %}
<option value="{{ tz }}"{% if tz == TIME_ZONE %} selected="selected"{% endif %}>{{ tz }}</option>
{% endfor %}
</select>
<input type="submit" value="Set" />
</form>
settings.py:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.timezone.TimeZoneMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
#'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'registration',
'django.contrib.humanize',
'n2w',
'n2api',
'dajaxice',
'pytz',
)
middleware class (timezone.py):
from django.utils import timezone
class TimeZoneMiddleware(object):
def process_request(self, request):
tz = request.session.get('django_timezone')
if tz:
timezone.activate(tz)
I think you are probably raising a NameError or something. Try importing pytz:
from pytz import common_timezones
...
...
return render(request, 'n2w/leads.html', {'timezones': common_timezones})
After upgrading my Python installation from 2.7.1 -> 2.7.3, I was able to import pytz flawlessly. Thanks for all your help!

request is missing from context

I'm trying to use django-localeurl in one of my project, but following the docs I just get an Error. What I want, is make work this code in the template:
{% load i18n %}
{% load localeurl_tags %}
{% get_available_languages as LANGUAGES %}
{% get_current_language as LANGUAGE_CODE %}
{% for lang in LANGUAGES %}
{% ifequal lang.0 LANGUAGE_CODE %}
<li class="selected">{{ lang.1 }}</li>
{% else %}
<li>{{ lang.1 }}</li>
{% endifequal %}
{% endfor %}
it's from: http://packages.python.org/django-localeurl/usage.html
I got this error
Caught AssertionError while rendering: URL must start with SCRIPT_PREFIX:
The problem is in this line:
<li>{{ lang.1 }}</li>
request.path is an empty string. but why? in the browser I can see 127.0.0.1/hu/, so If I'm right It should contain /hu/.
I created a brand new project just with django 1.3 and django-localeurl in the virtual environment, for simplicity.
My settings.py looks like (the important parts as I know):
LANGUAGES = (
('hu', 'Hungarian'),
('en', 'English'),
('sk', 'Slovakian'),
)
LANGUAGE_CODE = 'hu'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'localeurl.middleware.LocaleURLMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.request",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
)
INSTALLED_APPS = (
'localeurl',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
What Am I missing?
Edit 1:
I can put the request.path manually to the context:
def main(request):
return render_to_response( 'base.html', {'rpath': request.path})
than I use rpath in the template instead of request.path, but, but.... request.path should contain something, because of django.core.context_processors.request in the TEMPLATE_CONTEXT_PROCESSORS.
The problem was not related to localeurl, with the following view works:
return render_to_response( 'base.html', {}, context_instance = RequestContext(request))
I thought putting django.core.context_processors.request into TEMPLATE_CONTEXT_PROCESSORS do the job, but not.
Locale URL middleware hacks request.path I think what you're looking for is request.path_info
In your view, when returning a response, specify the context_instance like this:
from django.shortcuts import render_to_response
from django.template.context import RequestContext
return render_to_response('base.html',{'object':object},context_instance=RequestContext(request))