context: Django 3.1 app deployed to a AWS lambda with terraform. I have not set up my production settings yet, this is my dev server.
I'm using https://github.com/adamchainz/apig-wsgi
I noticed that messages from django.contrib.messages don't appear when attempting to get the api key with djangorestframework-api-key via the admin. It being on the lambda means I'm unable to access the lambda REPL to create the api key programmatically.
note: django-debug-toolbar also does not work and does so quietly, so I have a sneaking suspicion my context_processors settings are off so I don't have messages or DEBUG variables but I can't find the issue in my settings?? Below is my code without debug toolbar settings.
project/settings/base.py
DEBUG = True
INSTALLED_APPS = [
'app',
'rest_framework',
'rest_framework_api_key',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'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',
],
},
},
]
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'
AWS_STORAGE_BUCKET_NAME= [redacted]
AWS_DEFAULT_ACL = [redacted]
AWS_QUERYSTRING_AUTH= [redacted]
AWS_S3_REGION_NAME = [redacted]
AWS_LOCATION = [redacted]
USE_I18N = True
STATIC_URL = '/static/'
REST_FRAMEWORK = {
...
'DEFAULT_PERMISSION_CLASSES': [
"rest_framework_api_key.permissions.HasAPIKey",
]
}
project/wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
application = get_wsgi_application()
lambda_function.py
def install_secrets():
"""Add the secrets from the secret named by ENV_SECRET_ID to os.environ"""
import os
secret_id = os.environ.get('ENV_SECRET_ID')
if not secret_id:
return
import boto3
import json
session = boto3.session.Session()
client = session.client('secretsmanager')
response = client.get_secret_value(SecretId=secret_id)
overlay = json.loads(response['SecretString'])
os.environ.update(overlay)
def manage(event, context):
"""Entry point for running a management command. Supported formats:
- "migrate!"
- ["migrate"]
- {"command": ["migrate"]}
"""
if isinstance(event, dict):
command = event['command']
else:
command = event
if isinstance(command, str):
command = command.split()
install_secrets()
from django.core.wsgi import get_wsgi_application
get_wsgi_application() # Initialize Django
from django.core import management
return management.call_command(*command)
_real_handler = None
def lambda_handler(event, context):
"""Entry point for web requests"""
global _real_handler
if _real_handler is None:
print('No Cache, getting secrets.')
install_secrets()
from apig_wsgi import make_lambda_handler
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application()
_real_handler = make_lambda_handler(application)
return _real_handler(event, context)
default admin template admin/base.html where I'm expecting messages to show up (its just looping through the messages object, shouldn't need any JS or CSS to appear):
https://github.com/django/django/blob/2d8232fa716f5fe46eec9f35a0e90c2d0f126279/django/contrib/admin/templates/admin/base.html#L82
{% block messages %}
{% if messages %}
<ul class="messagelist">{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|capfirst }}</li>
{% endfor %}</ul>
{% endif %}
{% endblock messages %}
requirements.txt
Django>=3.1,<3.2
django-storages==1.11.1
apig-wsgi
psycopg2-binary
djangorestframework
djangorestframework-api-key==2.1.0
attempts:
tried hard reload F5 and all that
tried adding django debug toolbar and logging the apikey that shows up in messages in the admin, but didn't work because toolbar also doesn't show up (not shown in code above)
tried collectstatic on dev server
tried checking user sessions and seeing the messages on user sessions and there are messages there
A talented colleague fixed this. Adding
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
to your settings resolves the issue.
Credit goes to https://stackoverflow.com/users/1394697/flipperpa
Related
I created new project and can't find where the place where mistake was made.
Django versiob - 3.1.5
Python 3.7.4
TemplateDoesNotExist at /
index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.5
Exception Type: TemplateDoesNotExist
Exception Value:
index.html
Exception Location: C:\Users\user\PycharmProjects\Django learning\Portfolio\venv\lib\site-packages\django\template\loader.py, line 19, in get_template
Python Executable: C:\Users\user\PycharmProjects\Django learning\Portfolio\venv\Scripts\python.exe
Python Version: 3.7.4
Python Path:
['C:\Users\user\PycharmProjects\Django learning\Portfolio\landingpage',
'C:\Users\user\AppData\Local\Programs\Python\Python37\python37.zip',
'C:\Users\user\AppData\Local\Programs\Python\Python37\DLLs',
'C:\Users\user\AppData\Local\Programs\Python\Python37\lib',
'C:\Users\user\AppData\Local\Programs\Python\Python37',
'C:\Users\user\PycharmProjects\Django learning\Portfolio\venv',
'C:\Users\user\PycharmProjects\Django '
'learning\Portfolio\venv\lib\site-packages',
'C:\Users\user\PycharmProjects\Django '
'learning\Portfolio\venv\lib\site-packages\setuptools-40.8.0-py3.7.egg',
'C:\Users\user\PycharmProjects\Django '
'learning\Portfolio\venv\lib\site-packages\pip-19.0.3-py3.7.egg']
structure:
landingpage:
--forms #app:
urls
views
--landingpage:
templates:
index.html
settings.py
urls
others ...
landingpage/settings:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
project_name = "landingpage"
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# apps
'forms',
]
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',
]
ROOT_URLCONF = 'landingpage.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'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',
],
},
},
]
landingpage/urls:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('forms.urls')),
]
forms/urls:
from django.urls import path
from . import views
app_name = 'forms'
urlpatterns = [
path('', views.index, name='index')
]
views:
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'index.html')
landingpage/templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
Don't put your templates in landingpage folder. You should put your Templates in your app forms
Try to use this :-
Make a new folder in forms named templates and then make a new folder in templates named forms.
Your structure of folders should be like this :-
forms -> templates -> forms -> index.html
Use this in your views.py :-
def index(request):
return render(request, 'forms/index.html')
In my Django 2.0 site, I want to set the lang atribute of the html tag to the current locale's language. In my base.html which other templates extend, I use get_current_language in the following way
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE }}">
...
</html>
The site has translations for multiple languages. If I switch the language in the browser, I see the correct translations, but the lang attribute will always contain en.
In my settings.py I have
USE_I18N = True
LANGUAGE_CODE = 'en-us'
and based on the suggestion of Goran the following middleware order
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
The LANGUAGES setting is unset.
As suggested by Kostadin Slavov I have tried printing the language from the view. It seems that get_current_language calls django.utils.translation.get_language, so I have inserted the following in my view
from django.utils import translation
print(translation.get_language())
It prints the correct value (eg de when accessing the view with a browser set to German).
What else am I missing?
I tried to simulate your environment with these steps:
$ cd ~
$ python3 -m venv ~/venvs/mysite
$ source ~/venvs/mysite/bin/activate
$ pip install django==2.0.8
$ django-admin startproject mysite
Then I updated the generate code as in your example:
mysite/settings.py
...
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'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',
],
},
},
]
...
mysite/urls.py
from django.contrib import admin
from django.urls import path
from django.views.generic.base import TemplateView
urlpatterns = [
path('', TemplateView.as_view(template_name='base.html'), name='home'),
path('admin/', admin.site.urls),
]
templates/base.html
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE }}">
<body>
<pre>LANGUAGE_CODE = {{ LANGUAGE_CODE }}</pre>
<body>
</html>
With the Django generated code and my few above updates I can see different language code if I switch the language of my browser visiting http://localhost:8000/ after starting it with:
$ python manage.py runserver
Try my steps on your local environment and check if it works, and then compare your project to the code above.
Update
Try to use diffsettings to see "differences between the current settings file and Django’s default settings".
Had the same problem. In my case, the function was called async and always returned the default language.
SOLUTION: pass language from 'main' context.
Code like in this example:
def get_context_data( self, **kwargs ):
context = super().get_context_data(**kwargs)
lng_code = get_language() # -> 'de'
#sync_to_async
def get_data():
context['data1'] = Model1.objects.filter(language==get_language()) # get_language() -> 'en'
#sync_to_async
def get_data2():
...
#sync_to_async
def get_data3():
...
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(
asyncio.gather(
get_data1(),
get_data2(),
get_data3()
))
loop.close()
I am unable to load static files in production, whereas they work on local machine.
I have followed the steps in https://devcenter.heroku.com/articles/django-assets
as well as the existing answers but I am not able to make it run. I am overlooking something and would like the community's assistance.
Here is the partial settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ALLOWED_HOSTS = ['tryml.herokuapp.com','localhost']
# Application definition
INSTALLED_APPS = [
'web.apps.WebConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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',
]
ROOT_URLCONF = 'tryml.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'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',
],
},
},
]
WSGI_APPLICATION = 'tryml.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
Here is the wsgi.py file:
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tryml.settings")
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
Here is the html file trying to access the static content:
{% extends "web/base.html" %}
{% load static %}
{% block content %}
<div>
<img src="{% static 'web/img/target.jpg' %}" alt="Image could not be loaded"></img>
</div>
{% endblock %}
Here is the project structure:
tryml
--static
--web
--img
--target.jpg
--tryml
--settings.py
--wsgi.py
--urls.py
--web(web app)
--(urls,forms,templates,...)
--manage.py
--Procfile
--requirements.txt
--runtime.txt
One more observation, when I check the requests sent from my browser, it shows a 404 error for the static file(image) and says it tried to lookup here- ...herokuapp.com/static/web/img/target.jpg
Shouldn't it refer from STATIC_ROOT(staticfiles/web/img/target)?
EDIT-- The collectstatic command runs when the code is pushed on heroku,and it shows a successful copy step into app/staticfiles. Still, static file is not loading.
EDIT2--I ran the command python manage.py findstatic web/img/target.jpg as mentioned here: https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/#findstatic
It returned the file location on local machine but on heroku, it says 'No matching file found for 'web/img/target.jpg'.' Why is it not being located even after a collectstatic command has run successfully?
How does the production fetch of static files actually work? When I use {% static web/img/target.jpg %}, does it go to the STATIC_ROOT location to fetch it?
You have to serve the static file using nginx or you have to add path in urls py.
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
After doing 'find' on the remote heroku server from my machine, I came to know that the file is stored as 'target.JPG' and not 'target.jpg'.
I changed the access link accordingly in the template and it worked.
On the local machine, the CAPS do not seem to matter as I had already played around with them earlier.
Also, my git push to heroku never really changed the filename to 'target.jpg' because it doesn't consider changes in the caps of the filename unless told to as mentioned here - Changing capitalization of filenames in Git
Thank You.
I run the code last it's well,but taday when i input http://127.0.0.1:8000/,it show A server error occurred. Please contact the administrator.but I can't find anyerror in settings.py,and i revised the urls.py,then it show
enter image description here
it seems like there are two question
my urls.py
from django.conf.urls import url,include,patterns
from django.contrib import admin
from blog.views import *
#admin.autodiscover()
urlpatterns = patterns('',
url(r'^archive/$',archive),
url(r'^admin/',include(admin.site.urls)),
)
my setting.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.9.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'zzwayk(+k0m-+docu%uigkuymxlde34fx3$=syx#*3-i)8hlel'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'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',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'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',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'CCT'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
archive.html
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.timestamp }}</p>
<p>{{ post.body }}</p>
{% endfor %}
{% endblock %}
It seems there is no default (also called root, index or home) url in your urls.py
If you add something like this to your urls.py:
url("^$", views.index),
and also add a function named index in your views.py, you should have home page.
Alternatively, visit http://127.0.0.1:8000/archive/ or http://127.0.0.1:8000/admin/ because those are the urls you have something for.
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