我想創建一個表單,用戶將輸入他們的電子郵件。通常,電子郵件的驗證錯誤(空字段或不正確的格式)由瀏覽器顯示。驗證錯誤不會以Django的形式出現
使用的基本形式例子,一切都正確地顯示:
<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>
關於驗證錯誤,電子郵件瀏覽器通常會顯示一個彈出窗口,提示您應該在電子郵件地址中包含@ 此彈出消息顯示在表單的基本示例中,但不顯示阿賈克斯之一。我已經添加了一張圖片來使它更清晰.. – GiannisIordanou
嗯,一個問題肯定與附加的ID和類有關,這意味着CSS或JS。嘗試刪除您的自定義ID和課程。如果問題存在,則嘗試刪除可選標籤(div)。看到,當你使用基本的Django表單時,它會呈現具有必要屬性的所有必要元素。你可以比較你所期望的Django Form的HTML代碼和你的代碼。並嘗試一步一步來到Django Form版本來檢測問題。希望你會找到它。 – catscoolzhyk
例如,嘗試從輸入parent(div)的id(email-input-container)和頂級div remove類「row」中刪除。 你的模態問題呢? – catscoolzhyk