jdngao+bootstrap的ajax提交form表单Demo

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"}))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值