Empty catalog when internationalizing JavaScript code - django

I'm trying to set up Internationalization of JavaScript code in my Django application.
My Django app has a locale subdirectory with a properly generated djangojs.po file. The package definition is as follows:
# urls.py
js_info_dict = {
'packages': ('my_project',),
}
./manage.py makemessages worked well as the .po file contains all the to-be-translated strings but no JavaScript string ever gets translated on the website and the catalog is always empty.

I also had some problems with. This is how it works for me:
Add this to yr root urls.py:
js_info_dict = { 'domain': 'djangojs',
'packages': ('YOUR_PROJECT_NAME',), }
urlpatterns = patterns('',
#enable using translation strings in javascript
#source: https://docs.djangoproject.com/en/dev/topics/i18n/translation/#module-django.views.i18n
(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
)
In JS files use:
var somevar = gettext('Text to translate');
To compile django translation files: In a shell/terminal run from the project root (where 'apps', 'settings', etc lie):
#for "normal django files" (.py, .html):
django-admin.py makemessages --locale=de
#for javascript files. source: http://stackoverflow.com/a/3571954/268125
django-admin.py makemessages -a -d djangojs --locale=de
#to compile the translation files to machine code
django-admin.py compilemessages --locale=de

i added my_project to INSTALLED APPS in settings.py and that seemed to do the trick

Related

Static method returning empty list in Django

I am trying to run a Django app on local server. It works fine on mu Ubuntu machine but in mac, I can't get the CSS for
localhost:8000/admin
and
localhost:8000/docs to load.
On digging further, I found out that the static URL in main "urls.py" file
return an empty list instead of a URL pattern.
Does anyone have an idea why it is like that on the new mac system?
I have had the same issue. I was able to fix it manually by adding the following snippet to my urls.py file in the project (the urls.py file next to settings.py)...
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
. . .
if settings.TESTING_PRODUCTION:
urlpatterns += [
re_path(r'^static/(?P<path>.*)$', serve, {
'document_root': settings.STATIC_ROOT,
}),
]
I pulled this together from the Django Docs here.
I needed to do this so that I could test the "production" environment with manage.py runserver by manually setting DEBUG = False in settings.py which changes a few other URLs and also turns off trace printing in my code.
In my settings.py file, I have some code to set TESTING_PRODUCTION to True as well. But in actual production with a real web server, the code should set TESTING_PRODUCTION to False so that the static files can be served by the webserver directly and not through Django.

How to customize folder name when compilemessages in website insternationalization

For website Internationalization when run this command
django-admin compilemessages -l de
it produce the .po file under the locale folder like
locale/de/LC_MESSAGES/django.po
I want to rename LC_MESSAGES
How can I do this ???
Please help me
You should add a code snippet to rename the directory, this is the hard way but unfortunately, I don't know a better one.
import os
basedir = 'locale/de/' # Or you should add something like C:/locale/de
newname = 'Your script'
os.rename(os.path.join(basedir, newname)

Internationalization of static JS in Django

I want to translate a part of the JS in Django.
I've try the command python manage.py makemessages -d djangojs but it take only file in TEMPLATE_DIRS in the settings.py
I've try to set a JS in a template directory, and it work perfectly.
I've the djangojs.po and i can generate the .mo when i compile.
So the question is : How make message in static file?
I've found the same problem
Here
and
Here but no one answer who keep a good architecture.
Please, save me!
My architecture:
myapp
locale
static
myapp
js
try.js
template
myapp
try.html
views.py
urls.py
[...]
PS: Sorry for my english, i'm not native ;)
My error is when i set the STATIC_ROOT in settings.py. In fact this variable say at Django where stock Static when it do a CollectStatic on the server, i used her for say where found my static (Django can find all static whitout informations, it find static on a folder static on the project folder or on the app folder)
Finally :
set this in the urls.py of the pro
js_info_dict = {
'domain': 'djangojs',
'packages': ('app.kanboard',),
}
urlpatterns = patterns('',
[...]
#Internationalization Javascript
url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
)
In the template
<script type="text/javascript" src="{% url 'django.views.i18n.javascript_catalog' %}"></script>
In the JS in static/my_app/my_file.js
document.write(gettext('Ma chaine de caractère a traduire'))
After, we rule this command-line
python manage.py makemessages -d djangojs
Here, djangojs is the domain set in urls.py at the begin (It's a pseudo-convention)
At this time, we have a djangojs.po in the folder locale what we can compile as a standard .po.
Link of the doc : Here
Lik of my ticket where you can find a sample project and explication in english : The ticket
Good luck !

django-admin.py makemessages creates no files

I'm trying to enable translations for a django project and django-admin.py makemessages -l de doesn't seem to create any .po files, although there is a couple of {% trans ... %} in templates and a couple of gettext(...) in models for tests.
Accorgin to the documentation https://docs.djangoproject.com/en/1.7/ref/django-admin/#django-admin-makemessages, the command should search for translations in the whole project tree and create corresponding files in e.g. conf/locale directory if no setting is specified.
The only output I get is processing locale ru.
Any way to debug it or maybe well known pitfalls that I didn't find in google?
Let me answer my own question :)
The problem was that I:
Didn't import gettext as _ but did import gettext as t, thus makemessage didn't recognize translated strings in .py files
Tried to translate non-existing variables in templates instead of strings. {% trans some_var %} instead of {% trans "some_string" %}
Make sure you have the following settings available in your settings.py file:
DJANGO_ROOT = dirname(dirname(abspath(__file__)))
SITE_ROOT = dirname(DJANGO_ROOT)
USE_I18N = True
LOCALE_PATHS = (
SITE_ROOT + '/locale',
)
If the LOCALE_PATHS value is not set it does not know where it should create the locale directories and translation files, also you don't have to have the DJANGO_ROOT and SITE_ROOT values that's just for ease of use.

Install and Deploy Django app on Heroku

I often forget steps and wish there was a quick instructional guide on deploying a django project on Heroku.
How to Install and Deploy a Django app on Heroku?
I have posted a step-by-steps answer for steps that have worked for me.
You will get:
Django app both on heroku and your computer.
Postgres databases on both machines
git/bitbucket
authentication: login, logout, register, forgot pass, email authentication only (optional & default)
static files working on both machines
Bootstrap 3.0.3 included
South Migrations (instructions)
Requirements
heroku account
github/bitbucket account
mac with OSX (tested on 10.9)
UPDATE:
To do an installation the quick way, check out the other answer.
Folder structure
PROJECT_WRAPPER - it will hold everything, including PS
DJANGO_PROJECT - it will hold the code
DJANGO_APP - the main app will have that name
Anywhere you see those, replace with your real names!!!
Virtual Env
If you don’t have virtualenv, you need to get it. It will allow you to have separate installations of software for each project:
pip install virtualenv
then we create our project:
cd ~
mkdir PROJECT_WRAPPER && cd PROJECT_WRAPPER
virtualenv venv
now you have a dedicated folder that will contain independent installations and version of python, django, etc.
We activate and and start working on project the following way:
source venv/bin/activate
Postrges app
Just before we continue, we will install postgres.app. Grab it from:
http://postgresapp.com/
Install.
We will now hook up our environment with it:
PATH=/Applications/Postgres.app/Contents/MacOS/bin/:$PATH
Requirements.txt
Now we will need to install the following things:
Python, Django - no explanations required
South - Migrations of database (dev version of Django does not require it)
django-toolbelt - required by heroku and includes everything required for heroku
psycopg - postgres database
simplejson, mixpanel - these are optional, you could skip if you didn't like
So to create the requirements.txt file, we will get it ready from my git repository:
clone https://raw2.github.com/mgpepe/django-heroku-15/master/requirements.txt -o requirements.txt
Now with one command we will install everything from our requirements.txt:
pip install -r requirements.txt
Great, now we can verify that we have django with:
python -c "import django; print(django.get_version())"
Start a Django Project
Let’s start the project with this line and don’t forget the dot in the end:
django-admin.py startproject DJANGO_PROJECT .
Now if you type ls you should see a folder with your project name that contains your Django project.
To see if it all works run:
python manage.py runserver
DATABASE
Run the Postgres app.
Create a database with (I used my osx username):
createdb YOUR_DATABASE_NAME --owner=YOUR_OSX_USERNAME
change the DATABASES to look like this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'YOUR_DATABASE_NAME',
'USER': 'YOUR_OSX_USERNAME',
'PASSWORD': 'YOUR_DATABASE_PASSWORD', #might be empty string ''
'HOST': '127.0.0.1',
# 'PORT': '5432',
}
}
And also let’s hook up the South migrations. Your INSTALLED_APPS should look like that:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
)
Change the SECRET_KEY variable to something else than what it is.
Now if everything was fine you should be able to create the first tables with:
python manage.py syncdb
FIRST APP
Now make your first app in your project
python manage.py startapp DJANGO_APP
in the file: ~/PROJECT_WRAPPER/DJANGO_PROJECT/settings.py
add the DJANGO_APP app to the list in the variable INSTALLED_APPS. Should look like that:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'DJANGO_APP',
)
TEMPLATES
in settings file add the line:
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
In order for the templates to be well organized and working, we will copy base.html in one folder and the rest of templates in the app itself:
cd ~/PROJECT_WRAPPER/
mkdir templates
curl https://raw2.github.com/mgpepe/django-heroku-15/master/templates/base.html -o base.html
Now the rest of templates:
cd ~/PROJECT_WRAPPER/DJANGO_APP/
mkdir templates && cd templates
mkdir DJANGO_APP
curl https://raw2.github.com/mgpepe/django-heroku-15/master/DjMainApp/templates/DjMainApp/changepass.html -o changepass.html
curl https://raw2.github.com/mgpepe/django-heroku-15/master/DjMainApp/templates/DjMainApp/forgot_pass.html -o forgot_pass.html
curl https://raw2.github.com/mgpepe/django-heroku-15/master/DjMainApp/templates/DjMainApp/home.html -o home.html
curl https://raw2.github.com/mgpepe/django-heroku-15/master/DjMainApp/templates/DjMainApp/login.html -o login.html
curl https://raw2.github.com/mgpepe/django-heroku-15/master/DjMainApp/templates/DjMainApp/logout.html -o logout.html
curl https://raw2.github.com/mgpepe/django-heroku-15/master/DjMainApp/templates/DjMainApp/registration.html -o registration.html
curl https://raw2.github.com/mgpepe/django-heroku-15/master/DjMainApp/templates/DjMainApp/splash.html -o splash.html
AUTH SYSTEM WITH EMAIL
Since it has been lately fashionable to use email instead of username, we will do that too.
*NOTE: if you decide not to use it, you can skip this step BUT you have to edit the views and templates to use username instead of email. *
In settings add the following line:
AUTHENTICATION_BACKENDS = (DJANGO_PROJECT.backends.EmailAuthBackend’,)
then copy the file backends.py in our project directory:
cd ~/PROJECT_WRAPPER/DJANGO_PROJECT/
clone https://raw2.github.com/mgpepe/django-heroku-15/master/DjangoHerokuIn15/backends.py -o backends.py
HEROKU LOCALLY
You can simulate heroku working on your computer with Foreman. Let’s create the simplest configuration file:
cd ~/PROJECT_WRAPPER
echo "web: gunicorn DJANGO_PROJECT.wsgi" > Procfile
foreman start
Now that you see it working without errors stop it with CTRL+C
in settings all the way at the bottom add:
# HEROKU
###########################
# Parse database configuration from $DATABASE_URL
if os.environ.has_key('DATABASE_URL'):
import dj_database_url
DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
In your DJANGO_PROJECT/wsgi.py file and add the following to bottom:
from dj_static import Cling
application = Cling(get_wsgi_application())
STATIC FILES
Ideally you would server static files from Amazon or something like that. But for simple sites you could use Django. Setting it up requires you to append this in settings file:
# HEROKU STATIC ASSETS CONFIGURATION
################################
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
and put all static files in a specific folder. First go to your project folder with something like:
cd ~/PROJECT_WRAPPER/DJANGO_PROJECT/
and now you can just copy/paste the rest:
mkdir static && cd static
mkdir css && cd css
clone https://raw2.github.com/mgpepe/django-heroku-15/master/DjangoHerokuIn15/static/css/bootstrap.min.css -o bootstrap.min.css
clone https://raw2.github.com/mgpepe/django-heroku-15/master/DjangoHerokuIn15/static/css/styles.css -o styles.css
cd ..
mkdir js && cd js
clone https://raw2.github.com/mgpepe/django-heroku-15/master/DjangoHerokuIn15/static/js/bootstrap.min.js -o bootstrap.min.js
cd ..
mkdir img && cd img
In this last folder, you will put all images you need.
URL SETTINGS AND VIEWS
In urls.py copy these lines right before ‘example’:
url(r'^$', "pmfmain.views.splash", name="splash"),
url(r'^login$', "pmfmain.views.login_view", name="login"),
url(r'^signup$', "pmfmain.views.register", name="signup"),
url(r'^forgot$', "pmfmain.views.forgot_pass", name="forgotmypass"),
url(r'^logout$', "pmfmain.views.logout_user", name="logout"),
url(r'^dashboard$', "pmfmain.views.home", name="home”),
then copy views.py from my github repo to your DJANGO_PROJECT folder:
cd ~/PROJECT_WRAPPER/DJANGO_APP/
rm views.py
clone https://raw2.github.com/mgpepe/django-heroku-15/master/DjMainApp/views.py -o views.py
Do a find & replace replacing DjMainApp with your real DJANGO_APP name throughout the whole views.py
clone https://raw2.github.com/mgpepe/django-heroku-15/master/DjMainApp/forms.py -o forms.py
GIT
Some files need not be in git, so let’s set the config for this:
echo -e "venv\n*.pyc\n*.log\n*.pot\nstaticfiles" > .gitignore
and now lets commit:
git init
git add .
git commit -m ‘initial commit of django app’
Create a repository in git, then copy the git url (the one that ends in .git). Then:
git remote add origin THE_URL
git pull origin master
BITBUCKET ALTERNATIVE
If you don’t want to pay for github and you want your repository private, you can use bitbucket.
Login to your account
Create a new repository
Click add existing project
git remote add origin https://USERNAME#bitbucket.org/USERNAME/REPOSITORY_NAME.git
MULTIPLE HEROKU ACCOUNTS & KEYS
Even if you never have to have multiple heroku accounts, it is an easy way to setup and use it even for one account. So on we go:
cd ~
heroku plugins:install git://github.com/ddollar/heroku-accounts.git
the add a heroku account with:
heroku accounts:add personal
Enter your Heroku credentials.
Email:YOUR_HEROKU_EMAIL
Password: YOUR_HEROKU_PASSWORD
It says it in the console, and you have to do it:
Add the following to your ~/.ssh/config
Host heroku.personal
HostName heroku.com
IdentityFile /PATH/TO/PRIVATE/KEY
IdentitiesOnly yes
Go to your project folder with something like:
cd ~/PROJECT_WRAPPER
and then set the new account as:
heroku accounts:set personal
To create a new ssh KEY:
ssh-keygen -t rsa
When asked for name, write the full path and name as shown. then type your password or leave blank
Then add the keys both to your OSX and heroku:
heroku keys:add ~/.ssh/YOUR_KEY_NAME.pub
ssh-add ~/.ssh/YOUR_KEY_NAME
DEPLOYING HEROKU FILES
Now that you have keys in order, you should be able to do
heroku apps
and see that there are no apps. To add your first app:
heroku apps:create YOUR_APP_NAME
And now to upload to the server:
git push heroku master
now go to YOUR_APP_NAME.herokuapp.com to see your site!
DOMAIN SETUP
remains to be explained if anybody wants, let me know
NOTES
In-depth documentation at:
https://docs.djangoproject.com/en/1.6/intro/tutorial01/
https://devcenter.heroku.com/articles/getting-started-with-django
In my other answer, the process is well described, but takes time. So I have made a ready installation that is good to go in less than 15minutes.
https://github.com/mgpepe/django-heroku-15
If you'd prefer the full explanation with the long path see the answer below.
THESE ARE THE ERRORS WHICH I FIND WHILE WORKING ON DJANGO FOR 2 YEARS [ENJOY]
Dyno should be added/seen in heroku->resources and if it is not added in resources of Heroku then it means there is a problem in the
"Procfile"
web: gunicorn [django_project].wsgi --log-file -
"django_project" above is your project name , change it to your project name
Remember to do changes in the settings.py file
DEBUG=True
ALLOWED_HOSTS = ["your-app.herokuapp.com","127.0.0.1"]
add this in settings.py file
#->this should be in the middleware
'whitenoise.middleware.WhiteNoiseMiddleware',
#->this at the bottom
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
[ First do "pip install django-heroku" ]
place this at the top of settings.py file:
import django_heroku
place this at the bottom of "settings.py" file:
django_heroku.settings(locals())
Heroku only works with postgres, remember this
[ go to https://www.elephantsql.com/ ]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "",
"USER": "",
"PASSWORD": "",
"HOST": "",
"PORT": "5432",
}
}
Make Sure database in the background, if not running, start "postgres" in the services.msc.
[ This is in taskmanager->Services->postgresql->right click->start]
python manage.py migrate
go to "your app" in heroku and go to "settings" and select "Add buildpack" in the settings and select "python"
####################### Important ##############################
==> Create a new Git repository Initialize a git repository in a new or
existing directory
cd my-project/
git init
heroku git:remote -a iris-django-ml
==> Deploy your application
Commit your code to the repository and deploy it to Heroku using Git.
git add .
git commit -am "make it better"
git push heroku master
"run this command in your directory"
heroku login
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
restart again with deleting your git file of your working directory, delete heroku project (settings -> bottom)