【问题标题】:How to have Django raise ValidationError as Popup?如何让 Django 将 ValidationError 提升为 Popup?
【发布时间】:2021-02-15 00:10:13
【问题描述】:

我在我的一个表单上使用自定义 clean() 函数来满足条件字段要求。作为 DOM 的一部分,我可以使用 {{ form.non_field_errors }} 在我的模板上提出验证错误。我希望像默认错误一样弹出验证错误,但不知道如何。

这里是自定义的clean()函数:

class ReportForm(forms.Form):
    def clean(self):
        cleaned_data = super().clean()
        class_type = cleaned_data.get("class_type")
        class_other = cleaned_data.get("class_other")
        if class_type == "Other":
            if not class_other:
                msg = "Please fill out this field."
                raise ValidationError(msg)

我不知道在视图或模板中放置什么以使其显示为弹出窗口 - 我目前没有任何特别之处。 Django可以吗,还是我需要使用javascript?

【问题讨论】:

    标签: python django django-views django-forms django-templates


    【解决方案1】:

    通过“弹出窗口”,您可能指的是警告框。当用户尝试提交带有未完成的 html 所需输入的表单时,浏览器会生成它。您可以像这样添加必填字段:

        class BasicForm(forms.Form):
            name = forms.CharField(
                max_length = 35, 
                widget = forms.TextInput(
                    attrs = {
                        "id" : "name",
                        "class" : "input-class",
                        "placeholder" : "Insert Your Name",
                        "required" : "required", # <--- HERE YOU GO
                    }
                )
            )
    

    您可以强制浏览器生成警报框,即使表单中填充了 javascript。例如:

    btn = document.getElementById("button");
    inp = document.getElementById("name");
    
    // this piece of code will wait for the user to 
    // release a keyboard button having the input#name focused
    // then will call the function
    inp.addEventListener("keyup", event => {
      // I get the input value
      current_name = inp.value;
      // Checking if the name is longer than 8 characters
      if (current_name.length > 8) {
        // I will open an alert box
        alert("Your name is too long!");
      }
    });
    
    // this piece of code will wait for the user to 
    // click on the input#button, then will 
    // clear the input
    btn.addEventListener("click", event => {
      // Clearing the input value
      inp.value = "";
    });
    <form method="POST">
      <input type="text" id="name" class="input-class" required>
      <input type="button" id="button" value="clear"/>
     </form>

    【讨论】:

    • 谢谢,我不能/不想在表单中设置字段,因为只有在某些情况下才需要。我最终根据“某些情况”使用js创建/删除页面上的表单字段并根据需要添加标记。
    猜你喜欢
    • 2015-08-15
    • 1970-01-01
    • 2016-10-23
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2016-02-24
    相关资源
    最近更新 更多