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!
Related
I'm trying to create a Django app using Django crispy-forms.
settings.py
CRISPY_TEMPLATE_PACK = 'bootstrap3'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'face', #app name
'crispy_forms',
)
index.html
{% extends "base.html" %}
{% load crispy_forms_tag %}
{% block title %}
AuthorizedUser
{% endblock title %}
{% block content %}
<h1>Quote of the Day</h1>
<blockquote>{{quote}}</blockquote>
<p>Or, hit reload if you want a new one...</p>
<form method="POST" action="{% url %}" >
{% csrf_token %}
{{ form|crispy}}
<input type="hidden" name="quote" value="{{quote}}" />
<input type="hidden" name="access_token" value="{{access_token}}" />
<input type="submit" value="Set as my status!"/>
</form>
{% endblock content %}
When I'm running server it's raising an error
"TemplateSyntaxError at / 'crispy_forms_tag' is not a valid tag library: Template library crispy_forms_tag not found, trieddjango.templatetags.crispy_forms_tag,django.contrib.staticfiles.templatetags.crispy_forms_tag,django_facebook.templatetags.crispy_forms_tag,crispy_forms.templatetags.crispy_forms_tag".
What am I doing wrong? And how to fix it?
I've gone through that error just now.
Forgot to install django-crispy-forms
pip install django-crispy-forms
and refer it in settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
]
Once that was done, the problem was solved.
You should add Crispy Form tag in project setting .
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
]
add these crisp tag in your templates.html
{% load crispy_forms_tags %}
{% csrf_token %}
{% crispy form %}
Are you sure that the installation of Crispy forms worked ? you need to install django-crispy-forms.
Then, in your template index.html, you should use the crispy tag as following :
{% crispy name_form %}
instead of :
{{form|crispy}}
What's more, you should use
{% load crispy_forms_tags %}
not,
{% load crispy_forms_tag %}
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))
After spending too many hours on this, StackOverflow is for the rescue.
I configured my settings.py as below:
...
TIME_ZONE = 'Europe/Berlin'
LANGUAGE_CODE = 'de'
LANGUAGES = (
('en', u'English'),
('de', u'German'),
('fr', u'French'),
)
USE_I18N = True
USE_L10N = True
MIDDLEWARE_CLASSES = (
'django.middleware.locale.LocaleMiddleware',
'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.i18n',
'django.core.context_processors.request',
'django.core.context_processors.static',
'django.contrib.messages.context_processors.messages',
)
...
In my base.html file, I have a form as below:
<form action="/i18n/setlang/" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="/" />
<select name="language">
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}">{{ language.name_local }} ({{ language.code }})</option>
{% endfor %}
</select>
<input type="submit" value="Go" />
</form>
My urls.py:
urlpatterns = patterns('',
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^$', 'MainApp.views.index'), #root
)
In the same base.html file, I have on top {% load i18n %} and in the body, I have a sample {% trans "This is the title." %}. Before running the server, I did:
django-admin.py makemessages -l de
django-admin.py makemessages -l fr
The sample text above was picked up by makemessages, and I provided the respective translations for msgstr. After that, I did django-admin.py compilemessages. The command ran nicely and generated the .mo files in the respective locale folders.
I run the server and the the form does not work. From a another StackOverflow post, I was hinted to remove the #, fuzzy lines, which I did. What am I doing wrong?
Thanks!
You should put the LocaleMiddleware after the SessionMiddleware in your MIDDLEWARE_CLASSES:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
....
)
The order of middleware classes is important. The LocaleMiddleware uses session data to detect the user language, so it must come after the SessionMiddleware. It is also mentioned in the docs here https://docs.djangoproject.com/en/1.3/topics/i18n/deployment/#how-django-discovers-language-preference
Let's hope this works for you!
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.
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))