0

我有一个注册页面,其中包含以下代码:

在意见中:

def register_step2(request, value):
context={"type": value}
if request.method == 'POST':
    form = RegisterForm(request.POST)
    if form.is_valid():
        nric = form.cleaned_data['nric']
        name = form.cleaned_data['name']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        phonenumber = form.cleaned_data['phonenumber']
        dob = form.cleaned_data['dob']
        User.objects.create_user(nric, email, password)
        return HttpResponseRedirect('/')
return render_to_response('register.html', context, RequestContext(request))

在 register.html 中:

{% extends "base.html" %}
{% block subheader %}
{% if type == '0' %}
Are you..
{% endif %}
{% if type == '1' %}
Registration - Able Elder
{% endif %}
{% if type == '2' %}
Registration - Public
{% endif %}
{% endblock %}

{% block content %}
{% if type == '0' %}
<a href="/register/1">an elderly looking for something to do?</a>
<a href="/register/2">the public looking for someone to help you?</a>
{% else %}
<form action="/register/{{type}}/" method="post">{% csrf_token %}
<table class="center">
{% for field in able_form %}
<tr>
    <td>
        {{ field.label_tag }}: 
    </td>
    <td>
    {{ field.errors }}
    {{ field }}
    </td>
</tr>
{% endfor %}
<tr>
<td>
{{ able_form.non_field_errors }} 
</td>
</tr>
<tr>
<td colspan="2">
By clicking on "register" I agree with the terms and conditions.
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="register">
</form>
</td>
{% endif %}
{% endblock %}

在 context_processors.py 中(在 settings.py 中正确设置)

from forms import RegisterForm

def able_form(request):
    return {
            'able_form' : RegisterForm()}

在forms.py

class RegisterForm(forms.Form):
    nric = forms.CharField(max_length=NAME_MAX)
    name = forms.CharField(max_length=NAME_MAX)
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)
    email = forms.EmailField()
    postal_code = forms.IntegerField()
    phone_number = forms.IntegerField()
    date_of_birth = forms.DateField(widget=forms.DateInput)

据我了解,变量字段将显示字段错误,但是当我单击注册按钮时没有显示任何内容。我在这里做错了什么?

4

1 回答 1

2

随着您的更新,原因很明显:

您只是将一个空白表单传递给您的模板。

您在哪里假设带有request.POST数据的绑定表单返回到您的模板?创建一个新的实例RegisterForm(request.POST)不会神奇地改变模板中的表单实例(由上下文处理器返回)。

您的模板只会看到RegisterForm()- 如果要知道表单错误,它必须具有与 request.POST 数据绑定的表单。

    form = RegisterForm(request.POST)
    if form.is_valid():
       ....
    context['able_form'] = form # you must pass back the bound form if you want to see errors.
return render_to_response('register.html', context, RequestContext(request))

即使那样,您的上下文处理器也可能会覆盖此able_form键 - 我会完全删除上下文处理器。

如果您认为拥有它是一个好主意,那么您必须记住在那里或在您的视图中执行您的表单逻辑。

于 2012-06-11T02:10:15.840 回答