我的 HTML 模板中未显示表单验证错误

问题描述 投票:0回答:1

我在带有选项卡系统的单个 HTML 页面上使用 Django 开发了一个登录和注册系统。但是,我遇到了一个错误:注册后,页面就刷新了。为了排除故障,我通过将错误打印到控制台来进行调试。它打印出该表格无效。我故意提供了无效的详细信息来进行故障排除,例如输入类似于用户名的密码或不超过 8 个字符的密码。它在控制台中打印了该内容,但我希望它在每个字段的 HTML 模板中显示错误。所以,我写了一个登录注册视图。视图中一切似乎都正常,但它仍然没有显示 HTML 模板中的错误。

表格

class CustomUserCreationForm(UserCreationForm):
    email = forms.EmailField(label="Email", max_length=255, required=True)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name in self.fields:
            field = self.fields[field_name]
            field.widget.attrs.update({'class': 'u-full-width bg-light pb-2', 'placeholder': field.label})
            
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

浏览量

def login_register_view(request):
    if request.user.is_authenticated:
        return redirect('core:home')

    if request.method == 'POST':
        action = request.POST.get('action')

        if action == 'login':
             # login functionality

        elif action == 'register':
            registration_form = CustomUserCreationForm(request.POST)
            if registration_form.is_valid():
                user = User.objects.create_user(
                    username=registration_form.cleaned_data['username'],
                    email=registration_form.cleaned_data['email'],
                    password=registration_form.cleaned_data['password1']
                )
                user.save()
                return redirect('core:login_register')

    login_form = CustomAuthenticationForm()
    registration_form = CustomUserCreationForm()
    context = {
        'login_form': login_form,
        'registration_form': registration_form,
    }

    return render(request, 'accounts/login_register.html', context)

HTML 模板

<form method="post">
    {% csrf_token %}
    <div class="form-group">
        {{ registration_form.username.label_tag }}
        {{ registration_form.username }}
        {% if registration_form.username.errors %}
        <span class="error">{{ registration_form.username.errors }}</span>
        {% endif %}
    </div>

    <div class="form-group">
        {{ registration_form.email.label_tag }}
        {{ registration_form.email }}
        {% if registration_form.email.errors %}
        <span class="error">{{ registration_form.email.errors }}</span>
        {% endif %}
    </div>

    <div class="form-group">
        {{ registration_form.password1.label_tag }}
        {{ registration_form.password1 }}
        {% if registration_form.password1.errors %}
        <span class="error">{{ registration_form.password1.errors }}</span>
        {% endif %}
    </div>

    <div class="form-group">
        {{ registration_form.password2.label_tag }}
        {{ registration_form.password2 }}
        {% if registration_form.password2.errors %}
        <span class="error">{{ registration_form.password2.errors }}</span>
        {% endif %}
    </div>

    <button type="submit" name="action" value="register" class="btn btn-dark btn-full btn-medium">Register</button>
</form>
django django-forms user-registration django-errors
1个回答
0
投票

问题是,您需要使用

registration_form = CustomUserCreationForm()
重新初始化表单,以防它无效。因此,也消除了它的错误。 返回带有
POST
数据的表单。例如。像这样的:

    ...
    elif action == 'register':
        registration_form = CustomUserCreationForm(request.POST)
        if registration_form.is_valid():
            user = User.objects.create_user(
                username=registration_form.cleaned_data['username'],
                email=registration_form.cleaned_data['email'],
                password=registration_form.cleaned_data['password1']
            )
            user.save()
            return redirect('core:login_register')
        else:
            context = {
                'registration_form': registration_form,
            }
            return render(request, 'accounts/login_register.html', context)  
    ...
© www.soinside.com 2019 - 2024. All rights reserved.