Django之Form组件

新建数据库models.pyhtml

from django.db import models


# Create your models here.


class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    email = models.EmailField(max_length=32)

    def __str__(self):
        return self.username

views.py定义函数前端

from django.shortcuts import render, HttpResponse, redirect
# Create your views here.

from django import forms
# 导入django的forms
from django.forms import fields
from django.forms import widgets
# 导入forms里面的html插件
from app01 import models


# 导入app01数据库


# 基本须要掌握的几种:单选下拉框,多选下拉框,单选框,多选框,2种建立方式

# 定义一个类class,继承(forms.Form)
class TestForm(forms.Form):
    user = fields.CharField(
        required=True,  # 是否必填
        max_length=12,  # 最大长度
        min_length=3,  # 最小长度
        error_messages={},  # 错误信息
        widget=widgets.TextInput(attrs={'class': 'c1'}),
        label='用户',  # 前缀信息
        initial='请输入用户名',  # 输入框内信息
        help_text='123',  # 帮助信息,没用
        show_hidden_initial=False,  # 是否加入隐藏密码验证框
        # validators=[] 自定义验证规则
        disabled=True,  # 是否能够编辑
        label_suffix=':'  # label内容后缀
    )
    age = fields.IntegerField(
        label='年龄',
        max_value=12,
        min_value=2,
        error_messages={
            'max_value': '最大值必须小于或等于12',
            'min_value': '最小值必须大于2'
        }
    )

    email = fields.EmailField(
        label='邮箱'
    )

    img = fields.FileField()

    city = fields.TypedChoiceField(
        coerce=lambda x: int(x),
        # 1:value:文本内容
        choices=[(1, '村长'), (2, '镇长'), (3, '乡长'), ],
        initial=1,  # 默认值

    )
    hobby = fields.MultipleChoiceField(
        choices=[(1, '篮球'), (2, '足球'), (3, '棒球')],
        initial=(1, 2)
    )

    xoo = fields.FilePathField(
        path='app02',
    )
    # 下拉框
    # 单选下拉框select,值为字符串
    # new_test=fields.CharField(
    #     widget=widgets.Select(choices=[(1, '篮球'), (2, '足球'), (3, '棒球')],)
    # )用户提交过来是字符串,只有select里面有choices

    # new_test=fields.IntegerField(
    #     widget=widgets.Select(choices=[(1, '篮球'), (2, '足球'), (3, '棒球')],)
    # )用户提交过来是数字,只有select里面有choics

    # new_test = fields.ChoiceField(
    #     choices=[(1, '篮球'), (2, '足球'), (3, '棒球')],
    # )

    # 多选下拉框select,值为列表
    # user = fields.MultipleChoiceField(
    #     choices=((1,'上海'),(2,'北京'),),
    #     initial=[1,],
    #     widget=widgets.SelectMultiple
    # )

    # 打钩框
    # 单选打钩框checkbox,适用于赞成什么协议
    # user = fields.CharField(
    #     widget=widgets.CheckboxInput()
    # )

    # 单选框
    # 单radio,值为字符串
    # user = fields.CharField(
    #     initial=2,
    #     widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),))
    # )

    # 单radio,值为字符串
    # user = fields.ChoiceField(
    #     choices=((1, '上海'), (2, '北京'),),
    #     initial=2,
    #     widget=widgets.RadioSelect
    # )

    # 多选打钩框checkbox,值为列表,适用于爱好选择
    new_test = fields.MultipleChoiceField(
        initial=[2, ],
        choices=((1, '上海'), (2, '北京'),),
        widget=widgets.CheckboxSelectMultiple
    )


# 定义一个def函数,返回一个页面
def test(request):
    if request.method == 'GET':

        txt = "<input type='text' />"
        from django.utils.safestring import mark_safe
        txt = mark_safe(txt)

        # obj=TestForm('city':3)
        # 默认值
        obj = TestForm()
        return render(request, 'test.html', {'obj': obj, 'txt': txt})
    else:
        obj = TestForm(request.POST, request.FILES)
        if obj.is_valid():
            print(obj.cleaned_data)
            return render(request, 'test.html', {'obj': obj})

            # 例子:f=Foo(),class Foo: def __str__(self):return ' "<input type='text' />"
            #     obj=Foo()跟f=Foo(),
            # 调用f的时候输出foo的str方法<input type='text' />


from django.forms.models import ModelChoiceField


# 实例,用ModelChoiceField(第二种方式)
# 弊端,没法显示中文,依赖于在数据库models增长__str__方法,返回self.usernmae才能够显示

# 实例,建立一个页面,从数据库里面取数据(第一种方式,推荐这种方式)
class LoveForm(forms.Form):
    # user_id = fields.IntegerField(
    #     widget=widgets.Select(choices=models.UserInfo.objects.values_list('id', 'username'))
    # )
    user_id = fields.IntegerField(
        widget=widgets.Select()
    )
    price = fields.IntegerField()

    # 实例,用ModelChoiceField(第二种方式)
    user_id2 = ModelChoiceField(
        queryset=models.UserInfo.objects.all(),
        to_field_name='username',  # 做为value放在网页
    )

    # 重点:数据库的实时更新,super()先拷贝全部的静态字段,而后再赋值给self
    def __init__(self, *args, **kwargs):
        super(LoveForm, self).__init__(*args, **kwargs)

        self.fields['user_id'].widget.choices = models.UserInfo.objects.values_list('id', 'username')


def love(request):
    obj = LoveForm()
    return render(request, 'love.html', {'obj': obj})


class AJAXForm(forms.Form):
    user_id = fields.IntegerField(
        widget=widgets.Select(choices=[(0, 'alex'), (1, 'ago'), (2, 'agogo')])
    )
    price = fields.IntegerField(

    )


def ajax(request):
    if request.method == 'GET':
        obj = AJAXForm()
        # print(obj.cleaned_data)
        # 还没开始作验证,只是在前端显示了页面
        return render(request, 'AJAXForm.html', {'obj': obj})
    else:
        # 一.解决办法,给我钱我才跳,不给钱不跳
        ret = {'status': '没钱', 'message': None}
        import json
        obj = AJAXForm(request.POST)
        if obj.is_valid():
            print(obj.cleaned_data)
            # 跳转到百度,没有动做,由于不是form是ajax,因此没跳转
            ret['status'] = '钱'
            return redirect('http://www.styxypw.com')
            # return HttpResponse(json.dumps(ret))
        else:
            print(type(obj.errors))
            from django.forms.utils import ErrorDict
            # print(obj.errors.as_ul())
            # print(obj.errors.as_json())
            # print(obj.errors.as_data())
            ret['message'] = obj.errors
            # 二.错误新显示在页面上
            # return render(request, 'AJAXForm.html', {'obj': obj})
            return HttpResponse(json.dumps(ret))

url.py路由系统jquery

from django.contrib import admin
from django.urls import path, re_path
from app01 import views
from app02 import views as v2

urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', views.users),
    path('add_users/', views.add_users),
    path('edit_user/', views.edit_user),

    re_path('edit_user-(\d+)/', views.edit_user),

    path('test/', v2.test),
    path('love/', v2.love),
    path('AJAXForm/', v2.ajax),

]

test.html,测试下拉框与单选多选框页面ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    {{ txt }}
<form action="" method="POST" novalidate enctype="multipart/form-data">

    {% csrf_token %}
    <p>{{ obj.user.label }}{{ obj.user }}</p>
    <p>{{ obj.age.label }}{{ obj.age }}{{ obj.errors.age.0 }}</p>
    <p>{{ obj.email.label }}{{ obj.email }}</p>
    <p>{{ obj.img.label }}{{ obj.img }}</p>
    <p>{{ obj.city.label }}{{ obj.city }}</p>
    <p>{{ obj.hobby.label }}{{ obj.hobby }}</p>
    <p>{{ obj.xoo.label }}{{ obj.xoo }}</p>
    <p>{{ obj.new_test.label }}{{ obj.new_test }}</p>

    <input type="submit" value="提交">
</form>


</body>
</html>

love.html 数据库取数据页面数据库

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>西安</h1>
    <p>单价:{{ obj.price }}</p>
    <p>用户名:{{ obj.user_id }}</p>
    <p>{{ obj.user_id2 }}</p>
</body>
</html>
AJAXForm.html ajax的操做
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<form id="fm" action="/AJAXForm/" method="post" novalidate>
    {% csrf_token %}
    {{ obj.as_p }}
    <input type="submit" value="ajax提交" id="btn">
</form>

<script src="/static/jquery-3.1.1.js"></script>
<script>
    $(function () {
        $('#btn').click(function () {
            $.ajax({
                url: '/AJAXForm/',
                data: $('#btn').serialize(),
                type: 'POST',
                dataType: 'JSON',
                success: function (arg) {
                    //arg: 状态,错误的信息
                    if (arg.status == '钱') {
                        window.location.href = 'http://www.styxypw.com'
                    }
                    console.log(arg);
                }
            })
        })
    })

</script>

</body>
</html>
相关文章
相关标签/搜索