Django-表單使用
阿新 • • 發佈:2018-11-28
-----表單使用
1、定義表單類
1-1、
<form action="" method="post">
<input type="text" name="title">
<input type="date" name="pub_date">
<input type="submit">
</form>
1-2、 新建一個forms.py檔案,編寫Form類。
from django import forms
class BookForm(forms.Form):
title = forms.CharField(label="書名", required=True, max_length=50)
pub_date = forms.DateField(label='出版日期', required=True)
2、檢視中使用表單類
from django.shortcuts import render
from django.views.generic import View
from django.http import HttpResponse
from .forms import BookForm
class BookView(View):
def get(self, request):
form = BookForm()
return render(request, 'book.html', {'form': form})
def post(self, request):
form = BookForm(request.POST)
if form.is_valid(): # 驗證表單資料
print(form.cleaned_data) # 獲取驗證後的表單資料
return HttpResponse("OK")
else:
return render(request, 'book.html', {'form': form})
3、模板中使用表單類
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>書籍</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
</body>
</html>
4、模型類表單
class BookForm(forms.ModelForm):
class Meta:
model = BookInfo
fields = ('btitle', 'bpub_date')