Django是一個(gè)卓越的新一代Web框架,是用 Python 編寫(xiě)的一組類庫(kù)。Django表單是我們學(xué)習(xí)Django 的必學(xué)內(nèi)容。
1、直接在模版中按照xhtml或html5 語(yǔ)法寫(xiě)的form表單
<form action="/your-name/" method="post">
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
這種表單,直接在views中寫(xiě)
request.method == "GET" 時(shí),render 模版,在瀏覽器中顯示表單。
request.method == 'POST'時(shí),讀取表單中的數(shù)據(jù),再和數(shù)據(jù)庫(kù)交互。
2、繼承 Django Form class
需要在app下創(chuàng)建一個(gè)文件forms.py,如果已經(jīng)存在就不需要新建。
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
模版文件(name.html)中需要如下這樣寫(xiě)。
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
views 需要如下寫(xiě)。
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
3、以models 中定義的類來(lái)生成表單(Creating forms from models)
>>> from django.forms import ModelForm
>>> from myapp.models import Article
# Create the form class.
>>> class ArticleForm(ModelForm):
... class Meta:
... model = Article
... fields = ['pub_date', 'headline', 'content', 'reporter']
# Creating a form to add an article.
>>> form = ArticleForm()
# Creating a form to change an existing article.
>>> article = Article.objects.get(pk=1)
>>> form = ArticleForm(instance=article)
模版中寫(xiě)法參考第二種方法。
原文來(lái)自:知乎/黃哥