class TestForm(forms.Form): username = forms.CharField( required=True, label='账号', label_suffix=':', initial='Apollo', help_text='请输入您的登录账号', widget=widgets.TextInput(attrs={"class": "form-control"}), error_messages={ 'required': '账户不能为空' }, ) gender = forms.ChoiceField( label='性别', required=True, choices=((1, '男生'), (2, '女生'), (3, '保密')), initial=[2], widget=widgets.Select(attrs={"class": "form-control"}), error_messages={ 'required': '性别不能为空' } ) age = forms.IntegerField( required=True, max_value=150, min_value=16, label='年龄', widget=widgets.TextInput(attrs={"class": "form-control"}), error_messages={ 'required': '年龄不能为空', 'max_value': '年龄太大了', 'min_value': '未满16周岁,不能注册' } ) email = forms.EmailField( required=True, label='邮件', widget=widgets.TextInput(attrs={"class": "form-control"}) ) city = forms.ModelChoiceField( label='城市', queryset=City.objects.all(), widget=widgets.Select(attrs={"class": "form-control"}) )
def page(request): if request.method == 'GET': form = TestForm() return render(request, 'page.html', {'form': form}) else: res = {'username': None, 'err_msg': None} print(request.POST) form = TestForm(request.POST) if form.is_valid(): print(form.cleaned_data) return render(request, 'page.html', {'form': form.cleaned_data}) else: print(form.errors) res['err_msg'] = form.errors return JsonResponse(res)
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="/static/css/bootstrap.min.css"> <script src="/static/js/jquery-3.3.1.js"></script> <script src="/static/js/bootstrap.min.js"></script> <title>Apollo</title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="">{{ field.label }}</label> {{ field }} <span></span> </div> {% endfor %} </div> </div> <hr> <button id="btn" class="btn btn-success">点击按钮</button> <script src="/static/js/jquery-3.3.1.js"></script> <script> $(function () { $('#btn').click(function () { $.ajax({ url: '', type: 'post', data: { username: $('#id_username').val(), gender: $('#id_gender').val(), age: $('#age').val(), email: $('#id_email').val(), csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val() }, success: function (response) { if (response.username) { console.log(response); } else { $.each(response.err_msg, function (i, j) { $('#id_' + i).next().html(j[0]).addClass('pull-right has-error').css('color', 'red') }) } }, {# ajax结束#} }) }) }) </script> </div> </body> </html>