Problem with messages framework in Django 1.2 - django

I'm running Django 1.2 beta and trying out the new feature: message framework.
http://docs.djangoproject.com/en/dev/ref/contrib/messages/
Everything seems to work, but when I try to output the messages, I get nothing. Seems that messages variable is empty. I double checked all the settings, they seem to be just like in the manual. What could be wrong?
settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', #send messages to users
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
#debug tool
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.messages.context_processors.messages', #send messages to users
'django.core.context_processors.auth',
)
#Store messages in sessions
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage';
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
#'django.contrib.sites',
'django.contrib.admin',
'django.contrib.messages',
'debug_toolbar',
#my apps
#...
)
views.py
def myview(request):
from django.contrib import messages
messages.error(request, 'error test');
messages.success(request, 'success test');
return render_to_response('mytemplate.html', locals());
mytemplate.html
{% for message in messages %}
{{ message }}<br />
{% endfor %}
In template nothing is outputted.

You'll need to use a RequestContext in your call to render_to_response.
return render_to_response('mytemplate.html', locals(),
context_instance=RequestContext(request))
See the note a few screens down under this documentation section.

Related

Django messages framework - lack of i18n by default

By default django messages framework does not localize it's messages correctly.
For example in admin interface
As you can see all other things in admin panel are localized. The translation file exists. Here is my settings.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
...
]
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
]
LANGUAGE_CODE = 'ru' # I've tried 'ru-RU'
TIME_ZONE = 'Europe/Moscow'
USE_I18N = True
USE_L10N = True
USE_TZ = True
How to fix this? Thanks in advance. I have django version 3.0.6. This error also is absent in django 1.8
It was a breaking change from django/django#42b9a23 (Django 3.0+) that only updated the French translations.
You can patch DjangoTranslation.gettext to handle the smart quotes.
def _patch_gettext():
from django.utils.translation.trans_real import DjangoTranslation
_gettext = DjangoTranslation.gettext
def gettext(self, message):
text = _gettext(self, message)
if text is message and '“' in message:
new_message = message.replace('“', '"').replace('”', '"')
new_text = _gettext(self, new_message)
if new_text is not new_message:
return new_text
return text
DjangoTranslation.gettext = gettext
About patching
Subclass AppConfig in mysite/apps.py:
from django.apps import AppConfig
class MySiteAppConfig(AppConfig):
name = 'mysite'
def ready(self):
_patch_gettext()
Put the dotted path to that subclass in INSTALLED_APPS in mysite/settings.py:
INSTALLED_APPS = [
...
'mysite.apps.MySiteAppConfig',
]
Reference: https://docs.djangoproject.com/en/3.0/ref/applications/#configuring-applications

Django translations not working?

I want to translate my website to other language , i've configured my settings.py as it should be but no changes are happens.
I've created messages and i can see them inside my local folder, also i've compiled them successfully without any erors.
Here is my settings :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# My apps
'main',
# Third part apps
'captcha',
'jsonify'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LOCAL_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
LANGUAGE_CODE = 'en'
LANGUAGES = (
('ru', _(u'RU')),
('en', _(u'EN'))
)
My views:
from django.utils.translation import gettext as _
def main(request):
context = {
'title':_('Главная'),
}
return render(request, 'index.html', context)
Also i've loaded the i18n above inside my template where the translations happens index.html:
{% load static %}
{% load i18n %}
<title>{% block head_title %}{{title}}{% endblock %}</title>
I got it to work, instead of typing LOCALE_PATHS i typed LOCAL_PATHS, now everything is working just fine .

Django request.user is anonymous in views without login_required decorator

I am working on a Django (v2.0) app with django-allauth as auth backend. I'll explain my problem in steps:
User logs in -> user redirected to home page (can't access home page without login)
In the home page (after logging in), several calls are made for a particular view in the server.
Ex: https://mywebsite.com/api/getstuff/123
Problem: getstuff returns/prints data that is intended for a user who is NOT logged in.
getstuff is defined in urls.py as:
url(r'^api/getstuff/(?P<hash_code>[a-zA-Z0-9]{3})$', views.getstuff, name='getstuff')
in views.py: (views.getstuff)
#csrf_protect
#ensure_csrf_cookie
def getstuff(request,hash_code):
if request.user.is_authenticated:
#do stuff....
print('user is authenticated!')
return HttpResponse(hash_code+'foo-auth')
else:
#do other stuff..
print('user is NOT authenticated')
return HttpResponse(hash_code+'foo-un_auth')
I only see user is NOT authenticated being printed in my case. Shouldn't the output be user is authenticated since the user is already logged in? the request.user object is an AnonymousUser object. All the requests I make are from https.
few configurations from settings.py:
CSRF_USE_SESSIONS = True
CSRF_COOKIE_SECURE = True #tried removing this, still same result as above
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django_extensions',
'django.contrib.sitemaps',
'mysite.core',
'bootstrapform',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.github',
'allauth.socialaccount.providers.twitter',
'embed',
'channels',
'djcelery'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
AUTHENTICATION_BACKENDS = (
"allauth.account.auth_backends.AuthenticationBackend",
)
I tried clearing cache before accessing the website and logging in - still same result.
Am I missing something? What could be the problem?
Your use of if request.user.is_authenticated: is fine. Change the image src tag to use the domain that you logged into.
<img src="/api/getstuff/123">

NoReverseMatch implementing django-likes

Getting the following error when trying to install django-likes
NoReverseMatch at /post/25/
Reverse for '' with arguments '('posts-post', 25, 1)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Exception Location: /Users/Pete/.virtualenvs/innerlocal-mvp/lib/python2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 463
I'm not sure where to even start on this error, I've done a lot of searching, but nothing comes up.
My view that this is referring to:
def single_post(request, id):
post = get_object_or_404(Post, id=id)
...
return render(request, 'posts/single_post.html', locals())
with {% likes post %} in the html.
and this line highlighted from the resulting html:
<a class="liker" href="{% url like content_type content_obj.id 1 %}" rel="nofollow">{% trans "I Like" %}</a>
I'm using Django 1.7 so wouldn't be surprised if that was a problem.
Any help would be greatly appreciated!!
Extra settings as requested:
the urls.py lines (first, the app, second, the django-likes url:
url(r'^', include('posts.urls')),
(r'^likes/', include('likes.urls')),
and the urls.py for the posts app:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from views import PostDelete
urlpatterns = patterns('posts.views',
# (r'^', 'home'),
url(r'^$', 'all_posts', name='home'),
url(r'^post/(?P<id>\w+)/$', 'single_post', name='single_post'),
url(r'^new-post/$', 'new_post', name='new_post'),
url(r'^search/$', 'search', name='search'),
url(r'^delete/(?P<pk>\d+)/$', PostDelete.as_view(),
name='entry_delete'),
)
Installed apps:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django.contrib.sites',
....
'secretballot',
'likes',
)
Middleware classes:
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
'secretballot.middleware.SecretBallotIpMiddleware',
'secretballot.middleware.SecretBallotIpUseragentMiddleware',
'likes.middleware.SecretBallotUserIpUseragentMiddleware',
)
Template context processors:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
"allauth.account.context_processors.account",
"allauth.socialaccount.context_processors.socialaccount",
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.static",
"django.core.context_processors.media",
"django.contrib.messages.context_processors.messages",
)
Turns out that the app code needed a change:
In likes.html
from
<a class="liker" href="{% url like content_type content_obj.id 1 %}" rel="nofollow">{% trans "I Like" %}</a>
to
<a class="liker" href="{% url 'like' content_type content_obj.id 1 %}" rel="nofollow">{% trans "I Like" %}</a>
ie - the quotation marks around 'like'

About django translation template {% trans “something” %} in different systems

I know, I'm asking about something similar, requested a lot of times. But with a different point of view.
I'm working on a little django project. After developed the base functionalities, now I'm fighting with the multilanguage.
I was able to use a simple test template in my windows laptop. But when I copy this project to the test (CentOS) server it doesn't work.
Hereafter what I did.
The base environment (both systems) is virtualenv with python 2.7, django 1.5, mysql-python 1.2.3 and django-localeURL 1.5. gettext v.1.7.
These are the relevant options of settings.py (Note: I use django-localeURL application)
# Django settings for contact_site project.
import os.path
PROJECT_DIR = os.path.dirname(__file__) # this is not Django setting.
# ... skip
LANGUAGE_CODE = 'it'
#...skip
USE_I18N = True
USE_L10N = True
#...skip
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
# LocaleMiddleware after SessionMiddleware: it needs sessions
# commented out LocaleMiddleware to avoid conflict with LocaleURLMiddleware
# 'django.middleware.locale.LocaleMiddleware',
# LocaleURLMiddleware to manage multi language urls
'localeurl.middleware.LocaleURLMiddleware',
# CommonMiddleware after LocaleURLMiddleware or will not work APPEND_SLASH
'django.middleware.common.CommonMiddleware',
'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',
)
# ... skip
_ = lambda s: s
LANGUAGES = (
('en', _(u'English')),
('it', _(u'Italiano')),
('fr', _(u'Francais')),
)
LOCALE_PATHS = (
# in windows laptop
'C:/...skip.../virtualenvs/djprj/contact_site/locale',
# in centos staging server
# '/var/www/html/virtualenvs/djprj/contact_site/locale',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.core.context_processors.i18n',
'django.contrib.auth.context_processors.auth',
)
TEMPLATE_DIRS = (
# ...skip
os.path.join(PROJECT_DIR, "templates"),
)
INSTALLED_APPS = (
# localeurl to manage multi language urls. it must be the 1st one!
'localeurl',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# ... skip
# my application
'contact',
)
# ... skip
my project urls.py (the home only):
# ... skip
urlpatterns += patterns('',
url(r'^$', 'contact_site.views.home', name='home'),
)
my views.py (the home only):
#... skip
def home(request):
return render(request, 'minimalistic.html', {})
and finally my minimalistic template:
{% load debug_tags %}
{% load i18n %}
<!DOCTYPE html>
<html>
<head>
<title>TITLE</title>
</head>
<body>
{# {% set_trace %} #}
<p>{% trans "Hello" %}</p>
<p>{% blocktrans %}Hello guys{% endblocktrans %}</p>
lingua richiesta: {{ request.LANGUAGE_CODE }}
</body>
</html>
Then I produced the dictionaries of messages using
django-admin.py makemessages --all
I edited the dictionaries (using poedit)
and finally, running development server, in windows I saw the coveted result:
peeking from browser http://127.0.0.1:8000/it gave me Salve...
while getting http://127.0.0.1:8000/en gave me Hello ...
Unfortunatly in the stage system I got Hello ... from both URLs.
Just to be safe, in centos I tried even
django-admin.py compilemessages
this operation was ok, but without different results about the minimalistic.html template rendering
And last, yes, I cleared my browser cache between tests.
Any suggestion about what am I missing? How can I debug this strange behaviour?
Well, I'm sorry and a little embarassed.
Today, debugging django/utils/translate/trans_real.py, I have realized the presence of a subtle typo mistake in the staging server settings.py file.
I cannot count how many times yesterday I checked that configuration file, missing the point!
Sorry again