i18n添加后,Django注册破了

时间:2015-04-23 14:58:10

标签: python django django-registration django-i18n

我最近在我的Django应用程序中添加了i18n和l10n,但我的注册已经破了。我有这个:

  

对myApp / views.py

def register_user(request):
   if request.method == 'POST':
      form = MyRegistrationForm(request.POST)
      if form.is_valid():
         print "Is valid"
         form.save()
         return HttpResponseRedirect('/register_success/')
   args = {}
   args.update(csrf(request))
   args['form'] = MyRegistrationForm()
   print "Is invalid"
   return render_to_response('register.html', args, context_instance=RequestContext(request))
  

register.html

{% extends 'login_base.html' %}

{% block content %}

 <div class="col-sm-3 col-sm-offset-5"> 
   <h1> Join Now</h1>
     <form method='POST' action="{% url 'register' %}"> {% csrf_token %}
        {% if form.errors %}
          <p style="color: red;">
             Please correct the error{{ form.errors|pluralize }} below.
           </p>
       {% endif %}

    <table>
         {{ form.as_p }}
    </table>
        <input type='Submit' class='btn btn-primary btn-block'>
     </form>
 </div> 


{% endblock %}     
  

urls.py

# -*- coding: utf-8 -*-
from django.conf.urls import include, url, patterns
from django.contrib import admin
from django.conf import settings
from django.conf.urls.i18n import i18n_patterns


urlpatterns = i18n_patterns('',
    url(r'^$', 'myApp.views.home', name='home'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^auth/$', 'myApp.views.auth_view', name='auth'),
    url(r'^register/', 'myApp.views.register_user', name='register'),
    url(r'^register_success/', 'myApp.views.register_success', name='register_success'),   
)

My form

我在我的views中抛出了一些调试语句,这表明表单无效,但在我更改为添加对i18n的支持之前它已经有效。有没有人遇到过这个?

我尝试进行的一些更改是将所有HttpResponseRedirect('/foo/')更改为HttpResponseRedirect(reverse('foo')),并将表单操作从action='/register/'更改为action="{% url 'register' %}"

任何帮助都会很棒。如果我遗漏了任何重要细节,请告诉我。

我正在使用Django 1.7.4。

谢谢, erip

修改

在我的注册表中,我收到错误“Introduzca unafechaválida”。 (使用有效日期)。

我目前的日期格式是MM / DD / YYYY,但我使用的是西班牙语。我该怎么办?我已在下面的forms中确定了日期格式:

  

forms.py

class MyRegistrationForm(forms.ModelForm):
    """
    Form for registering a new account.
    """
    GENDER_CHOICES = (
        ('M', 'Male'), 
        ('F', 'Female'),
    )

    USER_TYPE = (
    ('S', 'Student'),
    ('T', 'Teacher'),
    ('B', 'Student/Teacher'),
    )

    email = forms.EmailField(widget=forms.EmailInput,label="Email")
    date_of_birth = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y'), label="Date of birth (MM/DD/YYYY)")
    gender = forms.ChoiceField(widget=RadioSelect, choices=GENDER_CHOICES, label="Gender")
    user_type = forms.ChoiceField(widget=RadioSelect, choices=USER_TYPE, label="Type of user")
    password1 = forms.CharField(widget=forms.PasswordInput,
                                label="Password")
    password2 = forms.CharField(widget=forms.PasswordInput,
                                label="Password (again)")

    class Meta:
        model = MyUser
        fields = ['email', 'date_of_birth', 'gender', 'user_type', 'password1', 'password2']

    def clean(self):
        """
        Verifies that the values entered into the password fields match

        NOTE: Errors here will appear in ``non_field_errors()`` because it applies to more than one field.
        """
        cleaned_data = super(MyRegistrationForm, self).clean()
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("Passwords don't match. Please enter both fields again.")
        return self.cleaned_data

    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
    user.set_adult()
        if commit:
            user.save()
        return user

1 个答案:

答案 0 :(得分:1)

用一些代码跟进我的最后评论......至少从这开始:

def register_user(request):
   args = {}
   args.update(csrf(request))

   if request.method == 'POST':
      form = MyRegistrationForm(request.POST)
      if form.is_valid():
         print "Is valid"
         form.save()
         return HttpResponseRedirect('/register_success/')
      else:
         print "Is invalid"  
         args = {}
         args.update(csrf(request))
         args['form'] = form
   else:
       args = {}
       args.update(csrf(request))
       args['form'] = MyRegistrationForm()

   return render_to_response('register.html', args, context_instance=RequestContext(request))

我并不为条件层次结构/重复代码感到骄傲,但它应该完成这项工作。