We need to make a translation into the Bashkir language on the site. This does not seem to exist in the locale django file. I'm trying to do this. In the settings.py file added.
import django.conf.locale
EXTRA_LANG_INFO = {
'ba': {
'bidi': False,
'code': 'ba',
'name': 'Bashkir',
'name_local': 'башкирский'
},
}
d = django.conf.locale.LANG_INFO.copy()
d.update(EXTRA_LANG_INFO)
django.conf.locale.LANG_INFO = d
LANGUAGE_CODE = 'ru'
LANGUAGES = (
('ru', 'Russian'),
('en','English'),
('ba', 'Bashkir'),
)
Now, when following the link, it writes that it cannot find the / ba page.(When switching to ru and en, the translation goes without problems).
I display links on the page as follows.
{% for language in languages %}
<a href="/{{ language.code }}/"}>{{ language.code }} </a>
{% endfor %}
in urls + = i18n_patterns added. Maybe there is some other way?
Or how to finish the given one?
Related
I'm putting together a project management website for my team using django. My base template includes a sidebar menu which contains a list of all projects and users, linking to a DetailView for that user or project, respectively.
My problem is that I need to provide the User and Project models to every view so that I can render that sidebar. I know how to add extra context; the problem is that I feel like I'm violating DRY by modifying the context at each level. Is it possible to simply redefine the base TemplateClass so that all child classes—ListView, DetailView, etc.—contain the modified context?
On a related note, if this is a terrible way to set up the project, let me know that as well.
You could use the template context processor:
myapp/context_processors.py:
from django.contrib.auth.models import User
from myapp.models import Project
def users_and_projects(request):
return {'all_users': User.objects.all(),
'all_projects': Project.objects.all()}
And then add this processor to the TEMPLATE_CONTEXT_PROCESSORS setting for Django version < 1.8:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'myapp.context_processors.users_and_projects',
)
And for Django version >= 1.8 add it to the context_processors list in the OPTIONS of the TEMPLATES setting:
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
...
'myapp.context_processors.users_and_projects',
],
},
},
]
Context processor will run for ALL your requests. If your want to run these queries only for views which use the base.html rendering then the other possible solution is the custom assignment tag:
#register.assignment_tag
def get_all_users():
return User.objects.all()
#register.assignment_tag
def get_all_projects():
return Project.objects.all()
And the in your base.html template:
{% load mytags %}
{% get_all_users as all_users %}
<ul>
{% for u in all_users %}
<li>{{ u }}</li>
{% endfor %}
</ul>
{% get_all_projects as all_projects %}
<ul>
{% for p in all_projects %}
<li>{{ p }}</li>
{% endfor %}
</ul>
I wrote a django web application and now I need to translate it to english. I followed the documentation but I keep getting this strange error:
ImproperlyConfigured at /i18n/setlang/ settings.DATABASES is
improperly configured. Please supply the ENGINE value. Check settings
documentation for more details. Request Method: POST Request
URL: http://192.92.149.139:8000/i18n/setlang/ Django Version: 2.0.3
Exception Type: ImproperlyConfigured Exception Value:
settings.DATABASES is improperly configured. Please supply the ENGINE
value. Check settings documentation for more details. Exception
Location: /home/mwon/venvs/arquivo/lib/python3.6/site-packages/django/db/backends/dummy/base.py
in complain, line 20 Python
Executable: /home/mwon/venvs/arquivo/bin/python3.6 Python
Version: 3.6.4 Python Path: ['/home/mwon/digitalocean/website_dev',
'/home/mwon/venvs/arquivo/lib/python36.zip',
'/home/mwon/venvs/arquivo/lib/python3.6',
'/home/mwon/venvs/arquivo/lib/python3.6/lib-dynload',
'/usr/lib/python3.6',
'/home/mwon/venvs/arquivo/lib/python3.6/site-packages',
'/home/mwon/venvs/arquivo/lib/python3.6/site-packages/django_styleguide-1.2.5-py3.6.egg',
'/home/mwon/venvs/arquivo/lib/python3.6/site-packages/Markdown-2.6.11-py3.6.egg',
'/home/mwon/venvs/arquivo/lib/python3.6/site-packages/bs4-0.0.1-py3.6.egg',
'/home/mwon/venvs/arquivo/lib/python3.6/site-packages/beautifulsoup4-4.6.0-py3.6.egg',
'/home/mwon/venvs/arquivo/lib/python3.6/site-packages/duc_preprocess-1.0-py3.6.egg',
'/home/mwon/venvs/arquivo/lib/python3.6/site-packages/simple_cnlp-1.0-py3.6.egg',
'/home/mwon/venvs/arquivo/lib/python3.6/site-packages/django_mongoengine-0.3-py3.6.egg']
Server time: Qua, 5 Set 2018 11:21:17 +0000
EDIT: and the settings.DATABASES:
{
'default': {
'ENGINE': 'django.db.backends.dummy',
'ATOMIC_REQUESTS': False,
'AUTOCOMMIT': True,
'CONN_MAX_AGE': 0,
'OPTIONS': {},
'TIME_ZONE': None,
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
'TEST': {
'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None
}
}
}
This is my urls.py:
urlpatterns = [
path('i18n/',include('django.conf.urls.i18n')),
]
urlpatterns += i18n_patterns(
path('admin/',admin.site.urls),
path('',include('arquivo.urls')),
prefix_default_language = True
)
and settings.py:
LANGUAGE_CODE = 'pt'
LANGUAGES = (
('en', 'English'),
('pt', 'Portuguese'),
)
USE_I18N = True
LOCALE_PATHS = [
os.path.join(BASE_DIR,'locale')
]
The translation seems to be working fine. The problem was when I included a form to select the language. I used the example code from documentation:
{% load i18n %}
<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}">
<select name="language">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
<input type="submit" value="Go">
</form>
Ok, so the problem was related with sessions. I'm using a MongoDB database with Django-MongoEngine and didn't turn on sessions support. So just added these two lines of code
SESSION_ENGINE = 'django_mongoengine.sessions'
SESSION_SERIALIZER = 'django_mongoengine.sessions.BSONSerializer'
to settings.py and everything started to work fine.
Now I'm developing a project, which should support two languages: English, as default, and Russian. It's pretty easy to do, using HTTP_ACCEPT_LANGUAGE header, the code is bellow:
babel = Babel(app)
#babel.localeselector
def get_locale():
return request.accept_languages.best_match(app.config["LANGUAGES"].keys())
Languages are hardcoded in application config file:
LANGUAGES = {
'en': 'English',
'ru': 'Russian'
}
But I also want to add a button, like Switch language to English. What is the best practice to realise it?
This is the solution I came across:
First you set a route that will handle the language change and will store the selected language on the session:
#app.route('/language/<language>')
def set_language(language=None):
session['language'] = language
return redirect(url_for('index'))
Secondly, you have to modify a little the code you have to get the selected language from the session:
#babel.localeselector
def get_locale():
# if the user has set up the language manually it will be stored in the session,
# so we use the locale from the user settings
try:
language = session['language']
except KeyError:
language = None
if language is not None:
return language
return request.accept_languages.best_match(app.config['LANGUAGES'].keys())
You have also to be able to access the CURRENT_LANGUAGE from the templates, so you can inject it:
#app.context_processor
def inject_conf_var():
return dict(
AVAILABLE_LANGUAGES=app.config['LANGUAGES'],
CURRENT_LANGUAGE=session.get('language',request.accept_languages.best_match(app.config['LANGUAGES'].keys())))
Finally, on the template you can choose the the language you want:
{% for language in AVAILABLE_LANGUAGES.items() %}
{% if CURRENT_LANGUAGE == language[0] %}
{{ language[1] }}
{% else %}
<a href="{{ url_for('set_language', language=language[0]) }}" >{{ language[1] }}</a>
{% endif %}
{% endfor %}
Application config.py includes the following constant:
LANGUAGES = {
'en': 'English',
'es': 'Spanish'
}
Hope this helps!
I am building a static site with Pelican and the i18n subsites plugin.
The way I understand it, you can override settings in pelicanconf.py with this plugin, but I don’t think the way I did it is working.
Pelicanconf.py:
I18N_SUBSITES = {
'nl': {
'SITENAME': 'Robin Berghuijs Design',
'INDEX_SAVE_AS': 'nieuws.html',
'MENUITEMS': [
('Nieuws','nieuws.html'),
],
},
'en': {
'SITENAME': 'Robin Berghuijs Design',
'INDEX_SAVE_AS': 'news.html',
'MENUITEMS': [
('News','news.html'),
],
}
}
Index.html output:
<nav id="menu"><ul>
<li>Contact</li>
</ul></nav><!-- /#menu -->
base.html template:
{% for title, link in MENUITEMS %}
<li>{{ title }}</li>
{% endfor %}
I get no errors upon site generation. More detail here.
Running pelican with --debug gives this.
As it turns out, the i18n subsites plugin was creating two new sites, with the old one left in the output folder. So there was a site in output/, one in output/nl/, and one in output/en/. Adding DELETE_OUTPUT_DIRECTORY = True and 'OUTPUT_PATH': '', to the Dutch i18n subsites settings solved the issue.
I am trying to modify the original Django administration template. I successfully managed to add custom content. But I would need this content to appear only when a table in my database is empty. Thus, I would like to pass some content to the template via the view but I cannot find it.
To be more specific, my extended admin template looks like this:
{% overextends "admin/index.html" %}
{% load i18n admin_urls %}
{% block content %}
{{ block.super }}
{% if is_empty %}
This hyperlink appears only when the table is empty
{% endif %}
{% endblock %}
and I would like to pass to the template to the variable is_empty either True or False, depending on whether the table is empty or not.
Any ideas how to do that?
Thanks a lot!
Create a template context processor that calculates the value of is_empty.
# in my_app/context_processors.py
from my_app.models import MyTable
def is_empty(request):
"""Returns a bool depending on whether MyTable is empty"""
return {'is_empty': not MyTable.objects.exists()}
Add your context processor to your template settings (note this step is slightly different for Django < 1.8).
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
...
'OPTIONS': {
'context_processors': [
...
'my_app.context_processors.is_empty',
],
},
},
]
You can then include {{ is_empty }} in any templates rendered with a request context. This includes admin views, generic class based views, and views that use the render shortcut.