Django 1.6:表示没有显示错误

时间:2014-06-15 07:37:17

标签: python django forms

我有一个注册表单,在模板中没有显示任何验证错误。如果提交的表单不正确,则只需使用空白字段再次呈现页面。我希望它能够显示注册表单的人所犯的错误。

这是我的表单

的模板
 <form action="" method="post" id="user_uploader" enctype="multipart/form-data"> {% csrf_token %}
{{ form.non_field_errors }}
<div class="">
    {{ form.name }}
</div>

{{ form.error_messages }}
{{ form.help_text }}
<div class="">
    {{ form.username }}
</div>

{{ form.non_field_errors }}
<div class="">
    {{ form.email}}
</div>

{{ form.non_field_errors }} 
<div class="">
    {{ form.password1 }}
</div>

{{ form.non_field_errors }}
{{ form.error_messages }}
<div class="">
    {{ form.password2 }}
</div>

<button class="btn btn-primary" type="submit" name="submit" id="ss-submit">SIGN UP</button>

这是我的forms.py

class UserCreationForm(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'password_mismatch': _("The two password fields didn't match."),
    }
    name = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'FirstName LastName'}))
    email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Please enter a valid email address so we can reach you.'}))
    username = forms.RegexField(label=_("Username"), max_length=50,
        regex=r'^[\w.@+-]+$',
        help_text=_("Required. 30 characters or fewer. Letters, digits and "
                    "@/./+/-/_ only."),
        error_messages={
            'invalid': _("This value may contain only letters, numbers and "
                         "@/./+/-/_ characters.")})
    password1 = forms.CharField(label=_("Password"),
        widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"),
        widget=forms.PasswordInput,
        help_text=_("Enter the same password as above, for verification."))

    class Meta:
        model = User
        fields = ("name","username","password1","password2","email")

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            User._default_manager.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(
            self.error_messages['duplicate_username'],
            code='duplicate_username',
        )

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        fullName = self.cleaned_data["name"]
        Email = self.cleaned_data["email"]


        if commit:
            user.save()
            userProfile = DoctorSeeker(user=user, name=fullName, email=Email)
            userProfile.save()

        return user

只是为了澄清我将注册信息保存到两个不同的模型中。

这是我的views.py

def signup_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST,request.FILES)
        if form.is_valid():
            new_user = form.save()
            new_user = authenticate(username=request.POST['username'],password=request.POST['password1'])
            login(request, new_user)

            return HttpResponseRedirect(reverse('index'))
    else:
        form = UserCreationForm()
    return render(request, "meddy1/signup.html", {'form': form,'usersignup':True})

1 个答案:

答案 0 :(得分:2)

您根本没有使用模板中从视图传递的form。您正在手动渲染每个表单元素。相反,您应该使用文档here

中所示的首选方式

来自该文件

<form action="/contact/" method="post">
    {% for field in form %}
        <div class="fieldWrapper">
            {{ field.errors }}
            {{ field.label_tag }} {{ field }}
        </div>
    {% endfor %}
    <p><input type="submit" value="Send message" /></p>
</form>

您可以添加div等来创建适合您的HTML。