jdngao+bootstrap的ajax提交form表单Demo,完整实例代码:
1,html代码
{% load bootstrap3 %}
<form enctype="multipart/form-data" id="form" method="post" class="form-horizontal"
action="{% url 'sqlapply:setting' %}">
<div class="form-group">
<div class="col-sm-6 col-sm-offset-0">
{% bootstrap_field form.host layout="horizontal" %}
{% bootstrap_field form.port layout="horizontal" %}
<div class="form-group">
<div class="col-sm-2 col-sm-offset-4">
<a class="btn btn-primary" onclick="save()">
保存
</a>
</div>
</div>
</div>
</div>
<script>
function save() {
$("div.help-block").remove();
var form = $("#form").serialize();
var res;
$.ajax({
url: "{% url 'sqlapply:setting' %}",
type: "POST",
data: form,
async: false,
timeout: 1000,
success: function (result) {
res = jQuery.parseJSON(result)
if (res["statcode"] === "0") {
var errors = res["data"];
for (var field in errors) {
var id_field = '#id_' + field;
$(id_field).parent().parent().addClass('has-error');
$(id_field).after('<div class="help-block">' + errors[field][0] + '</div>\n');
}
toastr.error("申请提交失败! " + ' <br /> 请查看报错信息,重新刷新页面后,再进行提交')
} else {
toastr.success("申请提交成功! " + '<br /> 请查看申请记录,不要重复提交')
}
},
error: function (result) {
alert( "POST失败,请联系管理员!");
}
});
};
toastr.options = {
"closeButton": true,
"debug": false,
"progressBar": true,
"preventDuplicates": true,
"positionClass": "toast-top-right",
"onclick": null,
"showDuration": "400",
"hideDuration": "1000",
"timeOut": "10000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
</script>
</form>
2、url文件:
urlpatterns = [
path('setting', setting.Setting.as_view(), name='setting'),
]
3、views文件:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import View
from sqlapply.forms import SettingForm
from sqlapply.models import GlobalConfig
import json
class Setting(LoginRequiredMixin, View):
def get(self, request, *args, **kwargs):
form = SettingForm()
GlobalConfig.objects.all().first()
return render(request, "sqlapply/setting.html", {"form": form})
def post(self, request, *args, **kwargs):
form = SettingForm(request.POST)
if form.is_valid():
globalConfig = GlobalConfig()
globalConfig.inception = form.cleaned_data
globalConfig.save()
response_data = {'statcode': '1', 'data': ''}
else:
response_data = {'statcode': '0', 'data': dict(form.errors)}
return HttpResponse(json.dumps(response_data))
4、form代码:
class SettingForm(forms.Form): host = forms.CharField(label='主机host',widget=forms.TextInput(attrs={'class': 'form-control'})) port = forms.CharField(label='端口',widget=forms.TextInput(attrs={"class":"form-control"})) user = forms.CharField(label='用户名',widget=forms.TextInput(attrs={"class":"form-control"}))