验证错误不会以Django格式显示

时间:2017-11-03 23:38:01

标签: python django forms

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

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

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

enter image description here

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

此外,即使验证中存在错误,也会显示模态。

这是我的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})

我的views.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>

1 个答案:

答案 0 :(得分:0)

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

所以,问题是如果你有一些验证错误,它们会出现在你的错误中。 div,只有你徘徊它们?如果是,那么它与您的cssjavascript相关。检查脚本和css文件。也许在某处您触发了.field-error元素。

关于模态外观。好吧,这是关于你的AJAX请求。

在您的代码中,无论如何,当HTTP Request将获得200代码的答案时,您将显示您的模态。这意味着,即使您没有有效的表单,也会向JsonResponse发回一些msg并将其带回您的页面,这意味着您的脚本每次都会触发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');
        }
    }
})}

有关处理AJAX请求中的错误的详细信息,请查看here