[英]validate and submit Django form (django-crispy-forms) with Ajax
我在Django和Web開發方面是新手。 我需要與Ajax一起提交Django表單(使用django-crispy-forms)的幫助如何:
驗證輸入
提交而無需重新加載
驗證失敗時顯示錯誤
現在,我可以提交表單,它將條目保存到數據庫中,但在此過程中將重新加載整個頁面。 我在下面包含了我的代碼的相關片段
//forms.py
class SubscriptionForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(SubscriptionForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.template_pack = 'bootstrap3'
self.helper.form_tag = True
self.helper.form_id = 'sub-form-1'
self.helper.form_class = 'form-inline'
self.helper.field_template = 'bootstrap3/inline_field.html'
self.helper.layout = Layout(
Div(Div(css_class='sub-form-notifications-content'),
css_class='sub-form-notifications'),
InlineField('name', id='subName'),
InlineField('email', id='subEmail'),
FormActions(Submit('submit', 'Notify me', css_class='form-control')),
)
class Meta:
model = Sub
fields = "__all__"
def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(
_("This email address is already in use. Please supply a different email address."))
return self.cleaned_data['email']
// views.py
from django.shortcuts import render, redirect
from .forms import SubscriptionForm
from .models import Sub
def index(request):
if request.method == 'POST':
sub_form = SubscriptionForm(request.POST)
if sub_form.is_valid():
sub_form.save()
# return redirect('landing:landing')
else:
sub_form = SubscriptionForm()
return render(request, 'landing/index.html', {'sub-form': sub_form})
//模板
...
{% crispy sub-form %}
...
//呈現的HTML格式
<form class="form-inline" id="sub-form-1" method="post">
<input type='hidden' name='csrfmiddlewaretoken'
value='tdiucOssKfKHaF7k9FwTbgr6hbi1TwIsJyaozhTHFTKeGlphtzUbYcqf4Qtcetre'/>
<div class="sub-form-notifications">
<div class="sub-form-notifications-content">
</div>
</div>
<div id="div_id_name" class="form-group">
<label for="subName" class="sr-only requiredField">Name</label>
<input type="text" name="name" maxlength="30" required placeholder="Name"
class="textinput textInput form-control" id="subName"/>
</div>
<div id="div_id_email" class="form-group"><label for="subEmail" class="sr-only requiredField">Email address</label>
<input type="email" name="email" maxlength="60" required placeholder="Email address"
class="emailinput form-control" id="subEmail"/>
</div>
<div class="form-group">
<div class="controls ">
<input type="submit" name="submit" value="Notify me" class="btn btn-primary" id="submit-id-sub-form"/>
</div>
</div>
</form>
我將盡力讓您了解如何輕松實現。
將onsubmit事件偵聽器添加到表單和錯誤塊,例如在顯示錯誤的表單下。
模板
<form class="form-inline" id="sub-form-1" method="post" onsubmit="sendData();">
...
</form>
<div class="error-block">
<!-- Here is the space for errors -->
</div>
現在,處理程序會將數據發送到視圖以進行驗證和保存
<script>
function sendData(e) {
e.preventDefault(); // don not refresh the page
var form_data = {
name: $('input[name="name"]').val(),
... other field values ...
}
$.ajax({
url: "{% url 'url-you-want-send-form-to' %}",
method: "POST",
data: form_data,
success: function(response) {
// here are the success data in the response
// you can redirect the user or anything else
//window.location.replace("{% url 'success-url' %}");
},
error: function(response) {
// here are the errors which you can append to .error-block
//$('.error-block').html(response);
}
})
}
</script>
在視圖中,您將以與提交表單時相同的形式接收數據,但是您不必將整個模板呈現給響應,而只需渲染已驗證表單中的錯誤,因此視圖將發送ajax POST請求必須與呈現表單的視圖不同。 您可以創建另一個將處理它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.