用户使用表单django在登录页面上选择语言

时间:2017-03-08 20:27:13

标签: html django django-forms django-views html-form

我有一个登录页面,其中包含以下格式:

  <form class="login-form" name="LoginForm" action="{% url 'login' %}" method="post">
  {% csrf_token %}
    <p>
        <table>
            <tr>
                <td>{{ form.username.label_tag }} </td>
                <td>{{ form.username }}</td>
            </tr>
            <tr>
                <td>{{ form.password.label_tag }}</td>
                <td>{{ form.password }}</td>
            </tr>
        </table>
    </p>
    <input class="button button-small" type="submit" value="Login" />
    <input type="hidden" name="next" value="{{ next }}" />
  </form>
  <a>English</a>
  <a>French</a>

我有一个看起来像这样的forms.py:

from django.contrib.auth.forms import AuthenticationForm 
from django import forms

class LoginForm(AuthenticationForm):
    username = forms.CharField(label="Username", max_length=30, 
                               widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'}))
    password = forms.CharField(label="Password", max_length=30, 
                               widget=forms.TextInput(attrs={'type': 'password', 'name': 'password', 'class': 'form-control'}))

和urls.py看起来像这样:

from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from stellar.forms import LoginForm
from stellar.views import index2
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('example.urls')),
    url(r'^login/$', auth_views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name = 'login'),
    url(r'^logout/$', auth_views.logout, {'next_page': '/login'}),
    url(r'^i18n/', include('django.conf.urls.i18n')),
]

基本上,如果用户点击英语或法语,页面的语言应该更改。我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

您应该在经过身份验证的表单下方创建另一个表单,例如this

{% load i18n %}

<form action="{% url 'set_language' %}" method="post">{% csrf_token %}

...

按照那里的指示,你会没事的!

如果有效,请告诉我。