Django无法显示表单错误

时间:2016-03-24 18:50:27

标签: django python-2.7 django-forms

我正在使用使用Django学习网站开发一书。

我已经从github中的fallowing路径Source code下载了源代码。我能够在我的Windows机器上运行该应用程序。

但由于某些原因,每次登录或注册后都会在提交后包含错误,这些错误都会在html页面中显示

请告诉我这是什么问题。我在浏览器控制台中看到的一个麻烦是

以下代码行显示错误消息

def register_page(request):
    form = RegistrationForm(request.POST or None)
    print request.method
    if request.method == 'POST' and form.is_valid():
        user = User.objects.create_user(
            username=form.cleaned_data['username'],
            password=form.cleaned_data['password1'],
            email=form.cleaned_data['email']
        )
        return HttpResponseRedirect('/register/success/')
    else:
        form = RegistrationForm()
    variables = RequestContext(request, {'form': form})
    print variables
    return render_to_response('registration/register.html', variables)

注册页面html代码:

{% extends "base.html" %}
{% block title %}User Registration{% endblock %}
{% block head %}User Registration{% endblock %}
{% block content %}
    print "ddd"
    {% if form.has_errors %}
        <p>Your username and password didn't match.
            Please try again.</p>
    {% endif %}

    <form method="post" action="">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="register" />
    </form>
{% endblock %}

登录页面代码:

{% extends "base.html" %}
{% block title %}User Login{% endblock %}
{% block head %}User Login{% endblock %}
{% block content %}
    {% if form.has_errors %}
        <p>Your username and password didn't match.
            Please try again.</p>
    {% endif %}
    <form method="post" action="">
        {% csrf_token %}
        <p><label for="id_username">Username:</label>
            {{ form.username }}</p>
        <p><label for="id_password">Password:</label>
            {{ form.password }}</p>
        <input type="submit" value="login" />
        <input type="hidden" name="next" value="/" />
    </form>
{% endblock %}

form.py

 import re

from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from django import forms


class RegistrationForm(forms.Form):
    print forms.Form;
    username = forms.CharField(
        label='Username',
        max_length=30
    )
    email = forms.EmailField(
        label='Email'
    )
    password1 = forms.CharField(
        label='Password',
        widget=forms.PasswordInput()
    )
    password2 = forms.CharField(
        label='Password (Again)',
        widget=forms.PasswordInput()
    )

    # password validation:
    def cleaned_password2(self):
        # all valid values are accessible trough self.clean_data
        if 'password1' in self.cleaned_data:
            password1 = self.cleaned_data['password1']
            password2 = self.cleaned_data['password2']
            if password1 == password2:
                return password2
        raise forms.ValidationError('Passwords do not match.')

    # username validation
    def cleaned_username(self):
        username = self.cleaned_data['username']
        if not re.search(r'^\w+$', username):
            raise forms.ValidationError('Username can only contain alphanumeric characters and the underscore.')
        try:
            User.objects.get(username=username)
        except ObjectDoesNotExist:
            return username
        raise forms.ValidationError('Username is already taken.')


class BookmarkSaveForm(forms.Form):
    url = forms.URLField(
        label='URL',
        widget=forms.TextInput(attrs={'size': 64})
    )
    title = forms.CharField(
        label='Title',
        widget=forms.TextInput(attrs={'size': 64})
    )
    tags = forms.CharField(
        label='Tags',
        widget=forms.TextInput(attrs={'size': 64})
    )

http://localhost:8000/static/style.css无法加载资源:服务器响应状态为404(未找到)

2 个答案:

答案 0 :(得分:1)

代码完全错误。

通过将method == 'POST'form.is_valid()合并到一张支票中,他们确保在 这些内容为假的情况下创建一个新的空表单。他们应该做的只是创建一个空表格,如果方法不等于&#34; POST&#34 ;;如果表单无效,则需要将该无效表单返回给模板,因为它包含错误。

所以你需要遵循正常模式,使用两个单独的if语句:

def register_page(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'],
                email=form.cleaned_data['email']
            )
            return HttpResponseRedirect('/register/success/')
        else:
            form = RegistrationForm()
        variables = RequestContext(request, {'form': form})

答案 1 :(得分:0)

I Remenber我遇到同样的问题,我做的是: 使用self.add_error将错误附加到表单中的特定字段。调用add_error()而不是forms.ValidationError(),如下所示:

密码验证:

    def cleaned_password2(self):
        # all valid values are accessible trough self.clean_data
        if 'password1' in self.cleaned_data:
            password1 = self.cleaned_data['password1']
            password2 = self.cleaned_data['password2']
            if password1 == password2:
                return password2
        msg =  'Passwords do not match.'
        self.add_error('password1',msg)