【问题标题】:Validation errors don't appear in Django form验证错误不会出现在 Django 表单中
【发布时间】:2018-04-16 18:40:49
【问题描述】:

我正在尝试创建一个表单,用户将在其中输入他们的电子邮件。通常,电子邮件的验证错误(空字段或格式不正确)由浏览器显示。

使用基本表单示例,一切都正确显示:

<form action="/notify-email/add/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

在我的情况下,如果没有验证错误,我会使用 ajax 请求来保存电子邮件并显示带有感谢消息的模式。但如果有验证错误,我只有在悬停时才能看到它们。

此外,即使验证出现错误,也会显示模态。

这是我的models.py:

from django.db import models


class NotifyEmail(models.Model):
    email = models.EmailField(max_length=255)
    date_added = models.DateField(auto_now_add=True)
    time_added = models.TimeField(auto_now_add=True)

    def __str__(self):
        return self.email

这是基于模型的表格:

from django import forms
from landing.models import NotifyEmail


class NotifyEmailForm(forms.ModelForm):
    class Meta:
        model = NotifyEmail
        fields = ["email"]

    def __init__(self, *args, **kwargs):
        super(NotifyEmailForm, self).__init__(*args, **kwargs)

        self.fields['email'].widget = forms.EmailInput(attrs={'placeholder': 'Email',
                                                              'required': True})

我的意见.py:

from django.shortcuts import render
from django.http import JsonResponse
from .forms import NotifyEmailForm



def add_notify_email(request):
    if request.method == "POST":
        form = NotifyEmailForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
            print("Email Added.")
            return JsonResponse({'msg': 'Data saved'})
        else:
            print("Error in Notify Form")
            return JsonResponse({"msg": "Error"})

    else:
        form = NotifyEmailForm()
    return render(request, "landing/home.html", {"form": form})

我的 urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [url(r'^notify-email/add/$', views.add_notify_email)]

html代码:

<div class="container-fluid" id="comingSoon">
    <div class="container">
        <h2>Coming Soon</h2>
        <h5>If you want to get notified when we go live, please enter your email below.</h5>
    </div>
    <div class="container" id="notify-email-container">
        <form action="/notify-email/add/" method="post" id="notify-email-form">
            {% csrf_token %}
            <div class="form-group row">
                <div class="col-sm-10" id="email-input-container">
                    <input class="form-control" type="email" name="email" placeholder="Your email...." maxlength="255" required id="id_email" />
                </div>

                 {% for error in form.email.errors %}
                    <div class="alert alert-error">
                        <p class="field-error"><i class="fa fa-exclamation-circle" aria-hidden="true"></i>{{ error|escape }}</p>
                    </div>
                {% endfor %}
                <div class="col-sm-2">
                    <button type="button" class="btn btn-block btn-primary" onclick="addNotifyEmail()" id="submit-notify-email">Notify Me</button>

                </div>
            </div>
        </form>
    </div>
</div>


<div class="modal" tabindex="-1" role="dialog" id="thanks">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Thank you</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>We would like to thank you for your interest.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script>
    function addNotifyEmail(e){
        var notifyEmailForm = $("#notify-email-form");
        var thanksModal = $("#thanks");

        $.ajax({
        type: 'POST',
        url: '/notify-email/add/',
        data: notifyEmailForm.serialize(),
        success: function(res){
                   thanksModal.modal('show')}

    })}
</script>

【问题讨论】:

    标签: python django forms


    【解决方案1】:

    我不确定我是否理解你的问题。

    所以,问题是如果您有一些验证错误,它们会出现在您的“错误”div 中,只有当您将它们悬停时?如果是,那么它与您的cssjavascript 有关。检查您的脚本和 css 文件。也许你在某个地方触发了.field-error 元素。

    关于模态外观。嗯,这是关于您的AJAX 请求。

    在您的代码中,无论如何您都会显示您的模式,而HTTP Request 将得到 200 代码的答案。这意味着即使您没有有效的表单,您也可以将一些消息发送回JsonResponse,并将其带回您的页面,这意味着您的脚本每次都会触发success,这就是您的模态出现的原因。

    不要只是发送一些JsonResponse({"msg": "Error"}),而是尝试使用它来处理错误。

    function addNotifyEmail(e){
        var notifyEmailForm = $("#notify-email-form");
        var thanksModal = $("#thanks");
    
        $.ajax({
        type: 'POST',
        url: '/notify-email/add/',
        data: notifyEmailForm.serialize(),
        success: function(res){
            if(res.msg !== "Error") {
                   thanksModal.modal('show');
            }
        }
    })}
    

    查看here,了解有关在AJAX 请求中处理错误的更多详细信息。

    【讨论】:

    • 关于验证错误,电子邮件的浏览器通常会显示一个弹出窗口,说您应该在电子邮件地址中包含@ 此弹出消息显示在表单的基本示例中但不是在 ajax 中。我添加了一张图片以使其更清晰..
    • 嗯,问题肯定与附加的 id 和类有关,这意味着 CSS 或 JS。尝试删除您的自定义 ID 和类。如果问题存在,则尝试删除可选标签(div)。看,当你使用基本的 Django Form 时,它会渲染所有必要的元素和必要的属性。您可以比较按预期工作的 Django Form 的 HTML 代码和您的代码。并尝试一步步来到Django Form版本来检测问题。希望你能找到它。
    • 例如,尝试从输入父级 (div) 中删除其 id (email-input-container) 并从顶部 div 中删除类“行”。你的模态问题呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 2016-03-20
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多