1. 程式人生 > >Django渲染自定義的表單

Django渲染自定義的表單

總urls.py中:

path('index/', views.index, name="index"),
path('form/', views.form, name="form"),

GET請求:

在APP下建立一個forms.py

"""
在這個檔案中,可以實現form表單的定製。
forms.py檔名是固定的,不能修改。
"""
from django import forms

# 1. 先宣告一個form類
class CustomForm(forms.Form):
    # 2. 定製兩個input標籤,用於輸入a和b的值
    # IntegerField()用來表明輸入框值的型別。
    # label引數對應的就是<label for="a">數字a:</label>
    # widget表示控制元件,input就是一個控制元件。如果預設控制元件提供的功能不夠用,那麼可以重新定製控制元件。比如input控制元件預設沒有顯示placeholder。
    # xxxField()和xxxInput()兩者進行區分:
    # xxxField()決定了輸入框中能輸入的資料型別。
    # 而xxxInput()一般和xxxField()是對應的,它xxxInput()一般是用來重寫控制元件的屬性。
    a = forms.IntegerField(label='數字A', widget=forms.NumberInput(attrs={'placeholder': '請輸入數字', 'class': 'number'}))

    # required表示該輸入框的值是否是必須填寫的,預設為True。
    b = forms.IntegerField(label='數字B', required=False)

# 3. 在views.py中,使用這個CustomForm類渲染表單。

在views.py檔案中:

from django.shortcuts import render
from django.http import HttpResponse
from .forms import CustomForm

# Create your views here.
def index(request):
    # 當載入首頁index.html的時候,不再使用預設的form表單了,需要將CustomForm這個定製的表單,渲染到index.html中。
    form = CustomForm()
    return render(request, 'index.html', {'form': form})

def form(request):
    """
    計算<form>表單中a和b相加之後的值。
    :param request:
    :return:
    """
    if request.method == "GET":
        # 此時的url地址:/form/?a=1&b=1
        # 獲取form表單的GET請求的引數
        a = request.GET.get('a', 0)
        b = request.GET.get('b', 0)
        return HttpResponse('結果:{}'.format(int(a) + int(b)))

在templates資料夾中的index.html中:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Form表單的用法</title>
    </head>
    <body>
        {# 如何渲染自定義的表單CustomForm? #}
        {# 1. <form>標籤和<button type="submit">需要自己去設定; #}
        {# 2. 自定義表單只生成input標籤; #}
        <form action="{% url 'form' %}" method="get">
            {{ form }}
            <button type="submit">計算</button>
        </form>
</body>
</html>

 

POST請求:

# 如果表單(CustomForm)提交的是POST請求,如何獲取POST請求的引數?

# 兩種方式:1.request.POST.get(); 2.使用is_valid和cleaned_data[];

第一種方式,與上面的get請求差不多,就不寫了

下面書寫第二種方式:使用is_valid和cleaned_data[];

在index.html中:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Form表單的用法</title>
    </head>
    <body>
        <form action="{% url 'form' %}" method="post">
            {% csrf_token %}
            {{ form }}
            <button type="submit">計算</button>
        </form>

    </body>
</html>

在views.py中寫:

def form(request):

    # 如果表單(CustomForm)提交的是POST請求,如何獲取POST請求的引數?
    # 兩種方式:1.request.POST.get(); 2.使用is_valid和cleaned_data[];
    # print(request.POST.get('a'))
    # 根據POST請求的資料,初始化CustomForm類的物件
    form = CustomForm(data=request.POST)
    if form.is_valid():
        a = form.cleaned_data['a']
        b = form.cleaned_data['b']
        return HttpResponse(a+b)
    else:
        return HttpResponse('資料不合法')

在APP下建立一個forms.py,其中的程式碼跟上面GET請求中的forms.py中一樣