验证错误未在表单上显示

时间:2016-10-08 10:56:36

标签: django django-forms django-allauth django-crispy-forms

我正在创建一个SignUp表单,它会显示验证错误,例如必填字段。但是,使用Django-Crispy-Forms时,不会出现验证错误。

我正在自定义Django-allauth的默认表单,这会引发ValidationError。但是,使用Django-Crispy表单时,表单上不会显示任何错误。

1.template

{% extends "base.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block content %}
<div class="big-box">
  <p><h1>{% trans "Sign Up" %}</h1></p>
  <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p>
  <div class="row">
    <div class="col-md-3">
      <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
        {% csrf_token %}
        {% crispy form %}
        {% if redirect_field_value %}
        <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
        {% endif %}
        <button type="submit">{% trans "Sign Up" %} &raquo;</button>
      </form>
    </div>
  </div>
</div>
{% endblock content %}

2.forms

from django import forms
from .models import Profile
from django.utils.translation import pgettext, ugettext_lazy as _, ugettext
from django.contrib.auth import get_user_model
from crispy_forms.helper import FormHelper


class SignupForm(forms.ModelForm):
    gender = forms.CharField(max_length=1, widget=forms.TextInput(attrs={'placeholder': _('Gender')}))
    #first_name = forms.CharField(max_length=50, label='',widget=forms.TextInput(attrs={'placeholder': 'First Name'}))
    first_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': _('First Name')}))
    last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': _('Last Name')})) 
    birthday = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': _('Birthday')}))
    location = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': _('Location')})) 

    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)

        self.fields['username'].widget.attrs.pop('autofocus')
        self.fields['first_name'].widget.attrs.update({'autofocus': 'autofocus'})
        self.helper =  FormHelper()
        self.helper.form_show_labels = False


    class Meta:
        model = get_user_model()
        fields = ('first_name', 'last_name', 'email', 'gender', 'birthday', 'location')

    def signup(self, request, user):
        # Save your user
        profile = Profile()
        profile.user = user
        profile.birthday = self.cleaned_data['birthday']
        profile.location = self.cleaned_data['location']
        profile.gender = self.cleaned_data['gender']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

        # Save your profile
        profile.save()
        user.save()

0 个答案:

没有答案