標籤:

Django表單的三種玩法。

本文由黃哥所寫,轉載請註明來源。

1、直接在模版中按照xhtml或html5 語法寫的form表單

<form action="/your-name/" method="post">n <label for="your_name">Your name: </label>n <input id="your_name" type="text" name="your_name" value="{{ current_name }}">n <input type="submit" value="OK">n</form>n

這種表單,直接在views中寫

request.method == "GET" 時,render 模版,在瀏覽器中顯示錶單。nrequest.method == POST時,讀取表單中的數據,再和資料庫交互。n

2、繼承 Django Form class

需要在app下創建一個文件forms.py,如果已經存在就不需要新建。

from django import formsnnclass NameForm(forms.Form):n your_name = forms.CharField(label=Your name, max_length=100)n

模版文件(name.html)中需要如下這樣寫。

<form action="/your-name/" method="post">n {% csrf_token %}n {{ form }}n <input type="submit" value="Submit" />n</form>n

views 需要如下寫。

from django.shortcuts import rendernfrom django.http import HttpResponseRedirectnnfrom .forms import NameFormnndef get_name(request):n # if this is a POST request we need to process the form datan if request.method == POST:n # create a form instance and populate it with data from the request:n form = NameForm(request.POST)n # check whether its valid:n if form.is_valid():n # process the data in form.cleaned_data as requiredn # ...n # redirect to a new URL:n return HttpResponseRedirect(/thanks/)nn # if a GET (or any other method) well create a blank formn else:n form = NameForm()nn return render(request, name.html, {form: form})n

3、以models 中定義的類來生成表單(Creating forms from models)

>>> from django.forms import ModelFormn>>> from myapp.models import Articlenn# Create the form class.n>>> class ArticleForm(ModelForm):n... class Meta:n... model = Articlen... fields = [pub_date, headline, content, reporter]nn# Creating a form to add an article.n>>> form = ArticleForm()nn# Creating a form to change an existing article.n>>> article = Article.objects.get(pk=1)n>>> form = ArticleForm(instance=article)n

模版中寫法參考第二種方法。(本文由黃哥所寫,轉載請註明來源。)

更詳細信息請看docs.djangoproject.com/

推薦閱讀:

Python科學計算與自動控制2-變數與簡單數據類型
Python的在線學習地址?
[15] Python循環語句(二)
odoo10 開發學習筆記2—簡單的請假模塊
Scrapy爬蟲框架教程(二)-- 爬取豆瓣電影TOP250

TAG:Python |