I am attempting to setup translation using Django's built in translation system. I followed Marina Mele's excellent tutorial at:
http://www.marinamele.com/taskbuster-django-tutorial/internationalization-localization-languages-time-zones#inter-settings
I am using Django 1.8-1.
After following the tutorial, I have the following settings:
settings.py
import os
from .confidential import KEY
from django.utils.translation import ugettext_lazy as _
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = KEY
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',
# third party useful apps
'crispy_forms',
# my apps
'plan_b_profile',
'django_countries',
'captcha',
)
CRISPY_TEMPLATE_PACK = 'bootstrap3'
CONFIRMATION_URL = 'http://127.0.0.1:8000/en/confirm/'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'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.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'younityb.urls'
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',
'django.template.context_processors.i18n',
],
},
},
]
WSGI_APPLICATION = 'younityb.wsgi.application'
# internationalization settings
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Montreal'
LANGUAGES = (
('en', _('English')),
('fr-ca', _('French (Canada)')),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Montreal'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static_in_env","static_root")
STATICFILES_DIRS =(
os.path.join(BASE_DIR,'static_in_pro'),
)
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(os.path.dirname(BASE_DIR),"static_in_env","media_root")
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
url(r'^captcha/', include('captcha.urls')),
]
urlpatterns += i18n_patterns(
url(r'^$', 'plan_b_profile.views.home', name='home'),
url(r'^confirm/','plan_b_profile.views.confirm', name='confirm'),
url(r'^admin/', include(admin.site.urls)),
)
The .po and .mo files are being generated and translations are being shown in my admin but I do not see my translations on my home view. In my templates I put the appropriate {% trans %} fields and also put {% load i18n %} at the top of the template. Any way to fix this?
Finally got the solution! Be careful with the names of your folders in your locale folder (folder with translation files). Make sure that for the filename, hyphens are underscored as follows:
French-Canada : fr-ca but the filename is fr_ca
Related
Django Version: 2.1
Problem: I am currently make a blog with Django and I am working on a feature which allows user to reset their password by sending the users email through. However I am not able to receive/send any emails through my PasswordResetView. What did I do wrong?
Things I've tried:
I have already set "Allow less secure apps: ON" in my google account.
I tried looking everywhere on Google and the answers provided are mostly asking me to try to Allow less secure apps on Google. It's been 24H I can't seem to find what have I done wrong..
I also tried using the EmailMessage class at my views.py. I am able to send email to myself. I don't think there is any issue with the authentication of my email.
Thanks in advance!
settings.py
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/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pwpcp#sy66r-ve4(o1o3_a3+2g6(zj)lp1g^q($mspw(kr6q$o'
# 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.apps.BlogConfig',
'user.apps.UserConfig',
'crispy_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 = 'django_blog.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 = 'django_blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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.2/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.2/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/2.2/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
CRISPY_TEMPLATE_PACK = 'bootstrap4' # go to crispy documentation online
LOGIN_REDIRECT_URL = 'blog-index'
LOGIN_URL = 'login'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword1234'
views.py
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from user import views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', auth_views.LoginView.as_view(template_name='user/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='user/logout.html'), name='logout'),
path('password-reset/',
auth_views.PasswordResetView.as_view(
template_name='user/password_reset.html'
),
name='password_reset'),
path('password-reset/done/',
auth_views.PasswordResetDoneView.as_view(
template_name='user/password_reset_done.html'
),
name='password_reset_done'),
path('password-reset-confirm/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(
template_name='user/password_reset_confirm.html'
),
name='password_reset_confirm'),
path('password-reset-complete/',
auth_views.PasswordResetCompleteView.as_view(
template_name='user/password_reset_complete.html'
),
name='password_reset_complete'),
path('', include('blog.urls')),
]
if settings.DEBUG: # only add this in when debug mode is on
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
make sure mention your apps on top of your installed apps
INSTALLED_APPS = [
'blog.apps.BlogConfig',
'user.apps.UserConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
]
I have run the python manage.py runserver command on my computer(windows 10) and it work but when I put all of codes on the google cloud platform compute engine(Ubuntu 16) and run the same command it shows all of the static files are not found. Do anyone knows how to fix it?
settings.py (ignore some irrelative parts)
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__)))
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_swagger',
'restaurants', # 餐廳APP
'webpack_loader', # 整合vue和django套件
'corsheaders' # 處理跨域請求套件
# 'gunicorn', # 部署用
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'foodies.urls'
TEMPLATES = [
{
'BACKEND':
'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '../static')],
'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 = 'foodies.wsgi.application'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, '../frontend/dist'),
)
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': '',
'STATS_FILE': os.path.join(BASE_DIR, '../webpack-
stats.json'),
}
}
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
# 允許所有header請求
CORS_ALLOW_HEADERS = ('*')
static files path
index.html
url.py
from django.contrib import admin
from django.urls import path, include
from rest_framework_swagger.views import get_swagger_view
from django.views.generic import TemplateView
schema_view = get_swagger_view(title='Pastebin API')
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('restaurants.urls')),
path('api-auth/', include('rest_framework.urls')),
path('api-view/', schema_view),
path('', TemplateView.as_view(
template_name="index.html"), name='index')
]
chrome error messages
compute engine status
I would suggest reading this:
https://docs.djangoproject.com/en/2.1/howto/static-files/deployment/
It has specific and exact instructions on the expected deployment of static files.
I tried to make custom 404 error page. I changed debug=True to debug=False and run local django server as >python manage.py runserver --insecure. Doing so website is loading css but didn't load images. All the images didn't load even after using --insecure. With debug=True all of css and images were loading.
I have removed some extra portion of settings.py hope below covers important ones.
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'login',
'upload',
'ckeditor',
'ckeditor_uploader',
'django_bootstrap_carousel'
]
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': [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',
],
},
},
]
WSGI_APPLICATION = 'TorrentSite.wsgi.application'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEFAULT_FROM_EMAIL = '-'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
EMAIL_PORT = 1025
MEDIA_ROOT = 'D:/projects/PyCharm projects/TorrentSite/media/'
MEDIA_URL = '/media/'
STATIC_ROOT = 'D:/projects/PyCharm projects/TorrentSite/upload/static/'
STATIC_URL = '/static/'
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from upload import views
from TorrentSite import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
handler404 = 'upload.views.custom_404'
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home_page, name='home_page'),
url(r'^games/', include('upload.urls')),
url(r'^contact/', views.contact_page, name='contact_page'),
url(r'^search/$', views.search_result, name='search-result')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
try add this in project/urls.py
...
from django.views.static import serve
...
urlpatterns = [
...
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }),
...
]
my settings file is:
I create message files for the language kk-ar, kk-kz, kk-latn to translate. and these language codes for same langugae in defferent wrinting system. but that not suport in django settings, so I add it to settings, but when i run the server django not show my translation.
this why?
Generated by 'django-admin startproject' using Django 1.8.5 and Python
3.4
gettext = lambda s: s
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
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.locale.LocaleMiddleware',
'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.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'task.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',
'django.template.context_processors.i18n',
],
},
},
]
WSGI_APPLICATION = 'task.wsgi.application'
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGES = (
('kk-kz', gettext('Kazakh')),
('kk-latn', gettext('Kazakh Latin')),
('kk-ar', gettext('Kazakh Arab')),
)
EXTRA_LANG_INFO = {
'kk-ar': {
'bidi': True, # right-to-left
'code': 'kk-ar',
'name': 'Kazakh Arab',
# unicode codepoints here
'name_local': u'\u0642\u0627\u0632\u0627\u0642\u0634\u0627',
},
'kk-latn': {
'bidi': False, # right-to-left
'code': 'kk-latn',
'name': 'Kazakh Latin',
# unicode codepoints here
'name_local': u'Qazaq',
},
}
# Add custom languages not provided by Django
laninfo = django.conf.locale.LANG_INFO
laninfo.update(EXTRA_LANG_INFO)
django.conf.locale.LANG_INFO = laninfo
# Languages using BiDi (right-to-left) layout
LANGUAGES_BIDI = global_settings.LANGUAGES_BIDI + ("kk-ar",)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
LANGUAGE_CODE = 'kk-ar'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = False
USE_TZ = True
and my url.py is like this:
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.i18n import i18n_patterns
from .views import home, home_files
urlpatterns = [
url(r'^(?P<filename>(robots.txt)|(humans.txt))$',
home_files, name='home_files'),
]
urlpatterns += i18n_patterns(
url(r'^admin/', include(admin.site.urls)),
url(r'^$', home, name='home'),
url(r'^i18n/', include('django.conf.urls.i18n')),
)
There are three steps to making translations work in Django:
Marking the strings as translatable
Creating the PO files
Compiling the PO files to MO files
The localization guide here: https://docs.djangoproject.com/en/1.8/topics/i18n/translation/#how-to-create-language-files has a good step by step guide to the process.
I am getting a TemplateDoesNotExist error on my django project and it is very frustrating because I have tried to make the app over and over again to but no avail. I was trying to see if I have made any noticeable errors but I cannot seem to find anything at all. I am making this project to help me learn django off of a website called OneMonth.
GitHub Project Files Here
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MAIN_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
SECRET_KEY = 'c#16w5r9r2)^n1%7#n4yp*l#itoq_&nw^%c(0f)(_0k0p2vs#w'
DEBUG = True
ALLOWED_HOSTS = []
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',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'coffeedapp.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 = 'coffeedapp.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
import dj_database_url
DATABASES['default'] = dj_database_url.config()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(MAIN_DIR, 'templates'),
)
STATICFILES_DIRS = (
os.path.join(MAIN_DIR, 'static'),
)
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'coffeedapp.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
(r'', include('core.urls')),
)
core/urls.py
from django.conf.urls import patterns, include, url
import core.views as coreviews
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'coffeedapp.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', coreviews.LandingView.as_view()),
)
Found that your DIRS in TEMPLATES setting is blank.
Have you tried to declare your templates folder inside the TEMPLATES instead of using TEMPLATE_DIRS = (
os.path.join(MAIN_DIR, 'templates'),
)?
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(MAIN_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.core.context_processors.i18n',
'django.contrib.messages.context_processors.messages',
],
},
},
]