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>
相關文章
相關標籤/搜索