[英]Validation errors don't appear in Django form
我正在嘗試創建一個表單,用戶可以在其中輸入他們的電子郵件。 通常,瀏覽器會顯示電子郵件的驗證錯誤(空白字段或格式不正確)。
使用基本表單示例,一切都可以正確顯示:
<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})
我的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">×</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>
我不確定我是否很好地理解了您的問題。
因此,問題是,如果您有一些驗證錯誤,那么僅當您將它們懸停在它們時,它們才會出現在“錯誤” div中。 如果是,則與您的css
或javascript
。 檢查您的腳本和CSS文件。 也許您在某個地方觸發了.field-error
元素。
關於模態出現。 好吧,這與您的AJAX
請求有關。
在您的代碼中,無論如何您都會顯示模態,而HTTP Request
將獲得200個代碼的答案。 這意味着即使您沒有有效的表單,您也會通過一些msg向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');
}
}
})}
在此處查看有關處理AJAX
請求中的錯誤的更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.