I am trying to translate my webpage using django-modeltranslation. I have complete the setup with the help of documentation provided but I am facing problem to display the model translated fields to templates. Can you help?
Here is what I have done.
# settings.py
def gettext(s):
return s
LANGUAGES = (
('en', gettext('English')),
('de', gettext('German')),
)
MODELTRANSLATION_TRANSLATION_FILES = (
'main.translation',
)
in app translation.py file
# project/app/translation.py
from modeltranslation.translator import translator, TranslationOptions
from .models import Post
class PostTranslationOptions(TranslationOptions):
fields = ('title', 'description')
translator.register(Post, PostTranslationOptions)
project urls.py file.
# urls.py
from django.contrib import admin
from django.urls import path, include
import debug_toolbar
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
path('admin/', admin.site.urls)
]
urlpatterns += [
path(r'^__debug__/', include(debug_toolbar.urls)),
]
urlpatterns += i18n_patterns(path('', include('main.urls')))
Views.py
# views.py
def ceo_dashboard(request):
post = Post.objects.all().select_related()
return render(request, 'main/dashboard_page.html', {'user': request.user, 'Posts': post})
template file
<h2 style="color:#0B2161;" >{{ post.title }}</h2>
<hr>
<p>{{ post.description }}</p>
<h5>Uploaded by : {{post.user}}</h5>
<hr>
Now I have no idea how to display these fields to templates.
You also need to add a Middleware called LocaleMiddleware, which activates translation for your project:
MIDDLEWARE = [
# ....
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware', # THIS ONE
'django.middleware.common.CommonMiddleware',
]
Read more about it in the Django documentation here: How Django discovers language preference
After that, you also need to add the language re-directer in your main template:
{% 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>
Now you can go to your admin and add Post where the django admin asks to enter different translation into the appropriate forms for the specified fields (in your case, 'title', 'description')
Hope this help you to solve the problem!
Related
I am back again with a Django Question. I am having issues with getting my login screen to work. I feel like maybe this is a simple issue that I am just not seeing. I am using the current versions of Python and Django. I am getting a NoReverseMatch error when trying to access my login page. Here is the code, along with some screen shots:
base.html:
<p>
Learning Log -
Topics -
{% if user.is_authenticated %}
Hello, {{ user.username }}.
{% else %}
log in
{% endif %}
</p>
{% block content %}{% endblock content %}
login.html:
{% extends "learning_logs/base.html" %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'users:login' %}">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">log in</button>
<input type="hidden" name="next" value="{% url 'learning_logs:index' %}"/>
</form>
{% endblock content %}
users/urls.py:
from django.urls import path
from django.conf.urls import url
from django.contrib.auth.views import LoginView
from . import views
app_name = 'users'
urlpatterns = [
# Login page
#path('login/', LoginView, {'template_name': 'users/login.html'}, name='login'),
path('login/', LoginView.as_view(template_name='users/login.html')),
]
Code location
Error message
Since you commented out the name='login' part. Django can no longer find a path(…) [Django-doc] with that name hence the error.
You should add the name=… parameter:
# users/urls.py
from django.urls import path
from django.contrib.auth.views import LoginView
from . import views
app_name = 'users'
urlpatterns = [
# Login page
path(
'login/',
LoginView.as_view(template_name='users/login.html'),
name='login' # name of the path
),
]
'learning.logs' is not a registered namespace.
Request Method:
GET
Request URL:
http://localhost:8000/users/login/
Django Version:
2.2.7
Exception Type:
NoReverseMatch
Exception Value:
'learning.logs' is not a registered namespace
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# my_apps
'learning_logs',
'users',
]
learning_log\urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('users/',include('users.urls', namespace='users')),
path('',include('learning_logs.urls', namespace='learning_logs')),
]
users\urls.py
from django.urls import re_path, path, include
from django.contrib.auth.views import LoginView
from . import views
app_name = 'users'
urlpatterns = [
# log in page
path('login/', LoginView.as_view(template_name='users/login.html'),name='login'),
]
learning_logs\urls.py
from django.urls import re_path
from . import views
app_name = 'learning_logs'
urlpatterns = [
# homepage
re_path('^$', views.index, name='index'),
# show all topics
re_path('^topics/$', views.topics, name='topics'),
# show dedicated topic
re_path('^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'),
# added new topic
re_path('^new_topic/$', views.new_topic, name='new_topic'),
# added new entry
re_path('^new_entry/(?P<topic_id>\d+)/$', views.new_entry, name='new_entry'),
# edit entry
re_path('^edit_entry/(?P<entry_id>\d+)/$', views.edit_entry, name='edit_entry'),
]
login.html
{% extends "learning_logs/base.html" %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'users:login' %}">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">log in</button>
<input type="hidden" name="next" value="{% url 'learning.logs:index' %}" />
</form>
{% endblock content %}
base.html
<p>
Learning Log -
Topics -
{% if user.is_authenticated %}
Hello, {{ user.username }}.
{% else %}
log in
{% endif %}
</p>
{% block content %}{% endblock content %}
In your template login.html you reference the url by the name learning.logs:index but the namespace you have created is learning_logs.
<input type="hidden" name="next" value="{% url 'learning.logs:index' %}" />
Just fix the typo in the template and you should be fine.
I extended the SignupView of django-allauth and created a url "/account-signup/" and also some minor changes in the template and I'm using the url name of my url. So, it keeps showing error that:
NoReverseMatch at /account-signup/
Reverse for 'account_login' not found. 'account_login' is not a valid view function or pattern name.
I've tried searching where the url name account_login is used in the template. Also, I've tried enabling the default URLs given by django allauth. It doesnt show error when the allauth URLs are included in the urls.py file.
/signup.html
{% extends "account/base.html" %}
{% load i18n %}
{% block head_title %}{% trans "Signup" %}{% endblock %}
{% block content %}
<h1>{% trans "Sign Up" %}</h1>
<p>{% blocktrans %}Already have an account? Then please sign in.{% endblocktrans %}</p>
<p>some content from sugat</p>
<form class="signup" id="signup_form" method="post" action="{% url 'my_app:custom_signup' %}">
{% csrf_token %}
{{ form.as_p }}
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<button type="submit">{% trans "Sign Up" %} »</button>
</form>
{% endblock %}
/my_app/urls.py
from django.conf.urls import url
from .views import *
app_name = "my_app"
urlpatterns = [
url(r'^account-signup/$', AccountSignUp.as_view(), name="account_signup"),
]
/myproject/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^accounts/', include('allauth.urls')),
url(r'', include("my_app.urls")),
]
I newbie into Django, and I need make a I18N system. I have this url.py:
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name='home'),
path(r'^i18n/', include('django.conf.urls.i18n')),
]
And I made this html to change the language:
{% load i18n %}
<form action="/i18n/setlang/" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{request.path}}" />
<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="selected"{% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
<input type="submit" value="Go" />
</form>
But when I click in "Go" button, the server response is: Page not found (404), The current path, i18n/setlang/, didn't match any of these. I stay using python 3.6 and Django 2.0.4.
And I no have idea how can I solve it.
The problem was here:
path(r'^i18n/', include('django.conf.urls.i18n')),
I cut off r'^':
path('i18n/', include('django.conf.urls.i18n')),
and works!
I have that urls.py:
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(
r'^login/$',
'django.contrib.auth.views.login',
{'template_name': 'loyalty/login.html'},
name='login'
),
url(
r'^logout/$',
'django.contrib.auth.views.logout',
{'next_page': '/', },
name='logout'),
)
and have template login.html*:
{% extends "loyalty/auth.html" %}
{% load i18n %}
{% block auth_form %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<form action="" method="post" id="login-form">{% csrf_token %}
{% if form.username.errors %}{{ form.username.errors }}{% endif %}
{{ form.username }}
{% if form.password.errors %}{{ form.password.errors }}{% endif %}
{{ form.password }}
<input type="hidden" name="this_is_the_login_form" value="1" />
<input type="hidden" name="next" value="{{ next }}" />
<button type="submit" name="submit">{% trans 'Log in' %}</button>
</form>
{% endblock %}
and i have in settings.py:
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.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
But this gives me this error:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF cookie not set.
In administrative interface, I have same problem.
What can I do to solve this problem?
You probably aren't passing the Request context from your view.
Example:
def show_form(request):
form = MyForm()
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
return render_to_response("template_to_display.html", {'form':form}, context_instance = template.RequestContext(request))
Update: I would suggest rearranging your middleware. Try removing the localemiddleware or placing it at last. The django default is this
I solved this problem. Problem in browser. Tried an other browser and all works fine. Didn't understand why I had this problem, because I tried clean cache and cookies.