1. 程式人生 > >[py]django表單

[py]django表單

messages http port pos list orm quest .text req

參考

django form的作用

1、生成html標簽

2、驗證輸入內容

form生成表單

zhuji/forms.py

- 實例化表單
- 定制form錯誤信息
- 定制表單類型


from django import forms


class UserInfo(forms.Form):
    user_type_choice = (
        (0, u'普通用戶'),
        (1, u'高級用戶'),
    )
    user_type = forms.IntegerField(widget=forms.widgets.Select(choices=user_type_choice,
                                                               attrs={'class': "form-control"}))
    email = forms.EmailField(error_messages={'required': "郵箱不能為空"})
    host = forms.CharField(error_messages={'required': "主機不能為空"})
    port = forms.CharField(error_messages={'required': "端口不能為空"},
                           widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "端口"})
                           )
    mobile = forms.CharField(error_messages={'required': "手機不能為空"},
                             widget=forms.Textarea(attrs={'class': "form-control", 'placeholder': "手機號碼"})
                             )

zhuji/views.py

from zhuji.forms import UserInfo


def user_list(request):
    obj = UserInfo()
    if request.method == "POST":
        user_input_obj = UserInfo(request.POST) #實例化form表單
        if user_input_obj.is_valid():#form驗證通過
            data = user_input_obj.clean()#前端表單獲取成一個dict

            hostname = data['host']#取出host字段
            print(data)
            print(hostname)
        else:
            error_msg = user_input_obj.errors
            return render(request, "user_list.html", {'obj': user_input_obj, 'errors': error_msg})#錯誤信息返回
    return render(request, 'user_list.html', {'obj': obj})

templates/user_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>user_list</title>
</head>
<body>
<div>
    <form action="/user_list/" method="post">
        <p>用戶類型: {{ obj.user_type }} <span>{{ errors.user_type }}</span></p>
        <p>主機: {{ obj.host }} <span>{{ errors.host }}</span></p>
        <p>郵箱: {{ obj.email }} <span>{{ errors.email }}</span></p>
        <p>端口: {{ obj.port }} <span>{{ errors.port }}</span></p>
        <p>手機: {{ obj.mobile }} <span>{{ errors.mobile }}</span></p>
        <p><input type="submit"></p>
        {% csrf_token %}
    </form>
</div>
</body>
</html>

技術分享圖片

[py]django表單