I use Django 1.3.
I have a clean project with:
settings.py
import os, sys
# absolute path to the project
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# add to PYTHONPATH
sys.path.append(os.path.join(PROJECT_ROOT, "apps"))
LANGUAGE_CODE = 'ru-ru'
USE_I18N = True
USE_L10N = True
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',
)
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT,'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'i18n_app',
)
urls.py
urlpatterns = patterns('',
url(r'^$', 'i18n_app.views.test'),
)
i18n_app/views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def test(request):
return render_to_response('i18n_app/test.html', context_instance=RequestContext(request))
templates/i18n_app/test.html
{% load i18n %}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
{% trans "String for trans" %}
<br>
<br>
<br>
{% blocktrans %}And one more{% endblocktrans %}
</body>
</html>
From project's root i run this command:
D:\Django\projects\testi18n>django-admin.py makemessages -l ru
processing language ru
Then I fill out file django.po which was created after this command and do:
D:\Django\projects\testi18n>django-admin.py compilemessages --traceback
processing file django.po in D:\Django\projects\testi18n\conf\locale\ru\LC_MESSAGES
But all I see it's english strings.
I have found too much questions about this, but no one of them hasn't helped to me.
What I'm doing wrong?
Add to your settings:
ugettext = lambda s: s
LANGUAGES = (
('ru', ugettext('Russian')),
('en', ugettext('English')),
)
Create an empty folder named locale in your projects directory
Then from your projects directory run:
django-admin.py makemessages -l ru
This command will create a .po file inside your locale folder.Open that file and fill the empty msgstr "" fields with the desired translation of the msgid fields that sit above.
This is where you define the translation of the strings you marked for translation in the .html file.
After writing the translation of your strings run:
django-admin.py compilemessages
django's test server needs a restart to take in account locale files changes/apparition. Otherwise translation won't work.
Looks like the LANGUAGES setting is missing in your settings.py. Try putting in something like that:
ugettext = lambda s: s
LANGUAGES = (
('ru', ugettext('Russian')),
('en', ugettext('English')),
)
In addition make sure that 'django.core.context_processors.i18n' is in your MIDDLEWARE_CLASSES setting, otherwise you won't be able to change the language. See the docs for details.
What i don't understand - why do you use django-admin.py in your project directory? Basically you should use manage.py in your project directory.
./manage.py makemessages -l ru
Don't forget to set LOCALE_PATHS to your locale folders
Related
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()
Hi I am doing the djangogirls tutorial and have come across the OperationalError no such table: blog_post. This works perfect on my virtual environment, but I get the OperationalError after pushing to heroku.
I am using Django 1.7.7. More information on the error is available at: https://girlsblog.herokuapp.com/
I have done
python manage.py makemigrations
python manage.py migrate
initially in the beginning of the tutorial. Then I attempted to do it again and there are "No changes detected" and "No migrations to make"
This is my post_list.html
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published.date }}
</div>
<h1>{{ post.title }}</h1>
<p> {{ post.text|linebreaks }}</p>
</div>
{% endfor %}
{% endblock content %}
This is my .gitignore
myvenv
__pycache__
staticfiles
local_settings.py
db.sqlite3
Models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
Settings.py
"""
Django settings for mysite project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1l8)#&q8r_wwev1r9mm8q5ezz8p#)rvg(l4%(t^-t8s4bva2+r'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_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.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'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
import dj_database_url
DATABASES['default'] = dj_database_url.config()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
STATIC_ROOT = 'staticfiles'
DEBUG = False
try:
from .local_settings import *
except ImportError:
pass
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
blog/views.py
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post
from .forms import PostForm
# Create your views here.
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def post_new(request):
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
I am really new to this, so please forgive "simple" mistakes.
Old post, but does not appeared to be answered so I'll take a shot. I was led here via google after having a similar problem.
This issue is probably a missing database on the heroku side. If you are pushing via git, and db.sqlite3 is in your .gitignore, it will definitely be missing there, and will need to be created there. This was exactly my issue when fiddling with a pre-made example (where the db had not yet been created).
$ python manage.py migrate
on your heroku environment should fix it.
This is because on Heroku you've very likely got the postgresql backend installed, not sqlite. You need to configure your production deployment to correctly use postgresql... I'd give instructions on that but I have to figure it out now...
I encountered the same issue and found a solution on reddit. Use
git add -f db.sqlite3
Then commit, push, and finally pull on pythonanywhere.com.
Credits to reddit users elbuckez & jeans_and_a_t-shirt
I did two things to resolve this:
Typed python3 manage.py migrate in server console, as David Nugent above said.
In .gitignore file, I had to comment out db.sqlite3. I then committed and pushed this change, then went back into my server (in my case pythonanywhere, not heroku) and did git pull.
Run this command python manage.py migrate --run-syncdb after these commands
python manage.py migrate
python manage.py makemigrations
Include this statement in your models.py:
from django.contrib.auth.models import User
So I'm pulling apart a website with the front-end already built and have taken on the task of building out the backend, but I am new to django. I have managed to separate everything out accordingly (css, js, img's in a static folder, html files in a templates folder, etc) and so far have been able to set the index.html as the homepage to django. Within this index.html file, other html files (located in the templates folder along with the index.html file) are being loaded within tags of the index.html file. Currently all of the images, css, and js is coming through in the file, but the html files are not. I am referencing these html files as "name of file.html" However, I cannot seem to get these to load unless I move the templates folder into the static folder (alongside the css, images, js, etc.) and change the reference to "static/templates/name of file.html"
My project setup is as follows. Also I'm running django 1.7.
atmos_v4/
atmos_v4/
init__.py
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py
static/
css/
...
img/
...
js/
...
media/
...
templates/
index.html
...
My urls.py and settings.py are below. I have a feeling my TEMPLATE_DIRS and STATIC_ROOT may be set up incorrectly. If not, would someone be so kind as to tell me what I'm missing? Thank you!
settings.py:
"""
Django settings for atmos_v4 project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y=3ey3sv8lm1j358(2bgthtx0bzy_cjaxug#2npx029nfs#5i%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_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',
)
MIDDLEWARE_CLASSES = (
'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 = 'atmos_v4.urls'
WSGI_APPLICATION = 'atmos_v4.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
from os.path import join
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
STATIC_PATH = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = (
STATIC_PATH,
)
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="index.html")),
url(r'^admin/', include(admin.site.urls)),
)
index.html reference examples
<div id="wheelartist" style="position:absolute; top:131px; left:536px; z- index:999999;">
<div id="circleartist" class="circleartist">
<a id="homebuttonLink" href="artist_profile.html"><img id="homebutton" title="Home" src="/static/img/icons/user.png" alt=""></a>
<a id="msgsbuttonLink" href="messages.html"><img id="msgsButton" title="Messages" src="/static/img/icons/mail.png" alt=""></a>
<a id="directorybuttonLink" href="directory.html"><img id="directoryButton" title="Directory" src="/static/img/icons/book.png" alt=""> </a>
<a id="cartbuttonLink" href="shopping_cart.html"><img id="cartButton" class="shopingCart" title="Shopping Cart" src="/static/img/icons/shopping.png" alt=""></a>
<a id="contestsbuttonLink" href="contests_list.html"><img id="contestsButton" class="planet" title="Planet" src="/static/img/icons/planet.png" alt=""></a>
<a id="pointsbuttonLink" href="points.html"><img id="pointsButton" class="awards" title="Awards" src="/static/img/icons/awards.png" alt=""></a>
<a id="prefbuttonLink" href="preferences.html"><img id="prefButton" class="tools" title="Tools" src="/static/img/icons/tools.png" alt=""></a>
<a id="searchbuttonLink" href="search.html"><img id="searchButton" class="headphones" title="Search" src="/static/img/icons/music.png" alt=""></a>
<a id="mapbuttonLink" href="artist_careermap.html"><img id="mapButton" title="Career Map" src="/static/img/icons/map.png" alt=""></a>
<a id="profitsbuttonLink" href="artist_profits.html"><img id="profitsButton" title="Profits" src="/static/img/icons/profits.png" alt=""></a>
<a id="statsbuttonLink" href="artist_stats.html"><img id="statsButton" title="Stats" src="/static/img/icons/stats.png" alt=""></a> </div>
templates/
index.html
try to change to this structure
templates/
atmos_v4/
index.html
and inside the settings.py remove this
"from os.path import join"
EDIT: after you update your file now i see that you have bad index.html file, you need to use the built-in function for templates and url
https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#url
My django is not executing translations that i define in my *.po files.
I have my setup like this:
MainFolder:
locale
en
LC_MESSAGES
django.po
django.mo
de
LC_MESSAGES
django.po
django.mo
app1
settings.py
app2
....
in my settings.py i have everything enabled i think:
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = 'en'
LANGUAGES = (
('en', _('English')),
('de', _('German')),
)
TEMPLATE_CONTEXT_PROCESSORS = (
....
'django.core.context_processors.static',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
)
let's say my django.po file contains an example like this:
msgid "Home"
msgstr "Home22222"
and i use this in my template file:
{% trans "Home" %}
The home is not being replace by Home22222
It stays the same, even when i remove the LocaleMiddleware.
i did ran
makemessages --locale=en
and afterwards:
compilemessages
I am using Python 2.7 and django 1.6.4
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