Django表单错误未显示

时间:2011-08-10 21:04:53

标签: python django

我有一个表单验证程序,当它失败时,错误消息不显示。知道我错过了什么吗?

views.py:

def setup_onesheet(request):
    # if the form has been submitted
    if request.method == 'POST':
        if 'unverified_username' in request.POST:
            form = OnesheetURL(request.POST)
            if form.is_valid():
                ...

    form = OnesheetURL()
    variables = RequestContext(request, {
        'error_message': error_message,
        'form' : form,
    });
    return render_to_response('onesheet_setup/setup_new_onesheet.html', variables)

forms.py:

class OnesheetURL(forms.Form):
    unverified_username = forms.CharField(label='http://onesheet.com/', max_length=75, validators=[validate_slug])

模板:

<form method="post" action="/setup/new/" id="verify-identity" class="full">
    {% csrf_token %}
    <ul>
        <li>
            {{ form.unverified_username.errors }}
            {{ form.unverified_username.label_tag }}
            {{ form.unverified_username }}
            <p>Onesheet URL can only contain letters, numbers, underscores ( _ ) or hyphens ( - ).</p>
        </li>
    </ul>
    <input type="submit">
</form>

1 个答案:

答案 0 :(得分:1)

尝试:

def setup_onesheet(request):
    # if the form has been submitted
    if request.method == 'POST':
        if 'unverified_username' in request.POST:
            form = OnesheetURL(request.POST)
            if form.is_valid():
                ...
    else:
        form = OnesheetURL()

    variables = RequestContext(request, {
        'error_message': error_message,
        'form' : form,
    });
    return render_to_response('onesheet_setup/setup_new_onesheet.html', variables)