如何让 Django 将 ValidationError 提升为 Popup?

时间:2021-02-15 00:10:13

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

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

这是自定义 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?

1 个答案:

答案 0 :(得分: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>