不显示 Django 中的表单错误

Does not show forms errors in Django

我想显示所需的错误但没有显示它们。我在 form.py 中犯了自定义错误,但它没有显示我的当前或默认值,为什么?

当我提交空白表单时,我希望它出现,我创建的错误

这是我的代码 -->

home.html

{% extends "home/base.html" %}

{% block content %}
<h2>Sign up Form</h2>
<div class="frm">
<form method="post" novalidate>
  {% csrf_token %}
  {{form}}
    
  
  <button type="submit">sign up</button>
</form>
</div>

{% endblock %}

forms.py

from django import forms
from django.contrib.auth.models import User

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
User = get_user_model()



class SignUpForm(UserCreationForm):
    username = forms.CharField(max_length=30)
    username.error_messages['required'] = ('Username field is required')
    email = forms.EmailField(max_length=200)
    
    def __init__(self, *args, **kwargs):
            super(SignUpForm, self).__init__(*args, **kwargs)
            for field_name, field in self.fields.items():
                field.widget.attrs['class'] = 'inp'
            for field in self.fields.values():
                field.error_messages = {'required':'The field {fieldname} is required'.format(
                    fieldname=field.label)} 
            

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2','mob', )

        

views.py

from .forms import SignUpForm
from django.http import HttpResponseRedirect
from django.shortcuts import redirect


from django.contrib.auth.forms import authenticate
from django.contrib.auth import login


def home(request):
    form = SignUpForm(request.POST)
    if request.method=="POST":
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('/')
        else:
            form = SignUpForm()
    return render(request, 'home/home.html', {'form': form})

def about(request):
    return render (request, 'home/about.html')

谁能帮帮我? 我在 Google 上搜索了很多,但找不到解决方案

在您的 views.py 中,您调用表单的方式有误,您传递 POST 请求的方式也有误。应该是这样

def home(request):
    form = SignUpForm()    # here
    if request.method=="POST":
        form = SignUpForm(request.POST) # and here

        if form.is_valid():
            ...

或者这个,

def home(request):
        form = SignUpForm(request.POST or None)    # here
        if request.method=="POST":
            if form.is_valid():
                ...

另一个主要问题在的回答中提到。

当您的表单无效时,您将返回一个没有无效数据的干净表单。 您的 else 块似乎没有正确缩进。

def home(request):
    if request.method=="POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('/')
    else:  # << change indentation
        form = SignUpForm()
    return render(request, 'home/home.html', {'form': form})