即使没有尝试提交,也会出现 Django 表单错误列表

Django form errorlist appears even when there is no attempt to submit

我的页面在通过 GET 请求时已经显示错误“此字段为必填项。”,这是不可取的行为。我希望当用户实际尝试提交没有所需数据的表单时出现此错误。

这是我的表格Python class:

class Place_A_Bid_Form(forms.Form):
    listing = forms.CharField(widget=forms.TextInput(attrs={"type":"hidden"}))
    bid = forms.IntegerField(widget=forms.NumberInput(attrs={"class":"form-control"}),
    min_value=1)

表单的html:

<form action="{% url 'place_a_bid' listing.title %}">
                {% csrf_token %}
                <div class="form-row">
                    <div class="col">
                        {{ form }}
                    </div>
                    <div class="col">
                        <input class="btn btn-primary" type="submit" value="Place a bid">
                    </div>
                </div>
            </form>

并查看:

def details(request, listing):
    listing_obj = Listing.objects.get(title=listing)
    form = Place_A_Bid_Form({"listing":listing_obj.title})
    categories = Category.objects.all()
    user = User.objects.get(username=request.user.username)
    if listing_obj in user.created_listings.all():
        return render(request, "auctions/details.html", {
            "listing": listing_obj,
            "categories": categories,
            "creator": True
        })
    elif listing_obj in user.watchlist.all():
        return render(request, "auctions/details.html", {
            "listing": listing_obj,
            "categories": categories,
            "in_watchlist": True,
            "form": form
            })
    else:
        return render(request, "auctions/details.html", {
            "listing": listing_obj,
            "categories": categories,
            "in_watchlist": False,
            "form": form
            })

我做错了什么? 提前致谢。

错误是你的表单没有方法,所以默认为GET。应该是

<form action="{% url 'place_a_bid' listing.title %}" method="post">

现在为什么即使没有提交表单也会出现错误?

form = Place_A_Bid_Form({"listing":listing_obj.title}) 创建一个绑定表单,由于 bid 是必需的且缺失,因此会出现错误。

也许您打算用初始数据创建一个未绑定的表单,如下所示:

form = Place_A_Bid_Form(initial={"listing":listing_obj.title})

这将在您的 html 上创建外观相同的表单,但由于它未绑定,因此不会给出任何错误,除非它 已提交 bid 字段。

查看 docs on bound and unbound forms, and this answer 了解如何为每个人提供初始数据。