Django Crispy Form - "This field is required" - 加载时显示

Django Cripsy Form - "This field is required" - shows on load

当页面加载时,我看到错误 - “此字段为必填项”,输入表单 'Title' 以红板突出显示。我希望这应该只在按下保存按钮后显示。我可以使用 self.helper.form_tag 打开和关闭消息,但这种行为对我来说似乎不正确,它似乎在我单击保存之前尝试提交。

我是做错了什么还是这是预期的行为?如果是预期的,有没有办法将其更改为仅在保存后显示警告?

forms.py

from django import forms
from .models import Request, RequestDocument
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Field, Div, Layout

class RequestForm(forms.Form):
    title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'title'}))
    rfp_No = forms.CharField(widget=forms.TextInput(attrs={}), required=False)
    company_Name = forms.CharField(widget=forms.TextInput(attrs={}), required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        #self.helper.form_tag = False
        self.helper.help_text_inline = True
        self.helper.layout = Layout(
            Div(Field('title'), css_class='col-md-12', ),
            Div(
                Div(Field('rfp_No'), css_class='col-md-6', ),
                Div(Field('company_Name'), css_class='col-md-6', ),
                css_class='row',
            ),

        )

create.html

{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}

<form method="post">
    {% csrf_token %}
    {% crispy form %}
    <button type="submit" class=" d-block btn btn-lg btn-success mt-4 w-50 mx-auto">
        Save
    </button>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(){
   $(".active").removeClass("active");
   $("#link-create").addClass("active");
});
</script>

将 self.helper.form_show_errors = False 添加到 init 会隐藏错误,但这会阻止显示实际错误,例如超过最大长度。

我最终通过拆分表单中的 POST 和 GET 方法解决了这个问题。

forms.py

form = RequestForm()
    if request.method == 'POST':
       ##Do Post Stuff
    elif request.method == 'GET':
       ##Do Get Stuff
    else:
        context = {   
        }
    return render(request, "requests/create.html", context)