当我们在开发一个基于Django的Web应用时,提交表单和前后端交互是非常关键的环节,下面是提交表单与前后端交互的方法的完整攻略。
设置表单
- 创建一个表单类,该类必须继承自Django的
forms.Form
或modelforms.ModelForm
,并声明表单所需要的字段。
示例代码:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
- 在视图函数中使用表单实例化,将数据传递给模板并渲染:
示例代码:
from django.shortcuts import render, redirect
from django.core.mail import send_mail
from django.template.loader import get_template
from django.template import Context
from .forms import ContactForm
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# 获取表单数据
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
# 发送邮件
recipients = ['youremail@example.com']
if cc_myself:
recipients.append(sender)
send_mail(subject, message, sender, recipients)
# 返回成功信息
return redirect('success')
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
前后端交互
Ajax
- 安装jQuery库
示例代码:
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
- 在模板文件中添加一个表单
示例代码:
<form method="post" id="contact-form" action="{% url 'contact' %}">
{% csrf_token %}
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" class="form-control">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" id="message" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="sender">Sender</label>
<input type="email" name="sender" id="sender" class="form-control">
</div>
<div class="form-check">
<input type="checkbox" name="cc_myself" id="cc_myself" class="form-check-input">
<label for="cc_myself" class="form-check-label">Send a copy to myself</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
- 编写JavaScript代码,使用jQuery库通过Ajax发送表单数据:
示例代码:
$('#contact-form').submit(function(event) {
event.preventDefault();
var subject = $('#subject').val();
var message = $('#message').val();
var sender = $('#sender').val();
var cc_myself = $('#cc_myself').is(':checked');
$.ajax({
url: $(this).attr('action'),
type: "POST",
data: {
'subject': subject,
'message': message,
'sender': sender,
'cc_myself': cc_myself,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
dataType: "json",
success: function(data) {
alert(data.message);
},
error: function(xhr, errmsg, err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
});
Fetch API
- 在视图函数中使用JSONResponse序列化表单数据
示例代码:
from django.http import JsonResponse
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# 获取表单数据
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
# 发送邮件
recipients = ['youremail@example.com']
if cc_myself:
recipients.append(sender)
send_mail(subject, message, sender, recipients)
# 返回JSONResponse
return JsonResponse({'message': 'Your message has been sent successfully.'})
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
- 编写JavaScript代码,使用Fetch API发送表单数据
示例代码:
const form = document.querySelector('#contact-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
const subject = form.querySelector('#subject').value;
const message = form.querySelector('#message').value;
const sender = form.querySelector('#sender').value;
const cc_myself = form.querySelector('#cc_myself').checked;
fetch('{% url "contact" %}', {
method: 'POST',
body: JSON.stringify({
'subject': subject,
'message': message,
'sender': sender,
'cc_myself': cc_myself,
'csrfmiddlewaretoken': document.querySelector('input[name="csrfmiddlewaretoken"]').value
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(data => alert(data.message))
.catch(error => console.log('Error:', error));
});
在完成这些步骤后,您的Django应用程序就可以支持表单提交和前后端交互了。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Django之提交表单与前后端交互的方法 - Python技术站