Django学习--form(表单)
01 表单基础
1.1概念
在html中,一个表单的元素是<form>.....</form>,在表单里面允许visitor做输入文本,选择,提交对象等等工作。对于当中<input>元素,明白用户输入的数据应该被返回的,还有这个数据应该通过哪种HTTP方式返回数据
1.2http method
对于表单数据的传输,主要两种方式:post和get,其中get方式数据从url传递,比如https://docs.djangoproject.com/search/?q=forms&release=1,其中数据为q='fomrs',release=1. 另一种方式是post方式,其数据在
1.3.过程
比如用户登录过程,用户在界面上输入用户名和密码,经过post方式提交后其数据就会被传入到对应的视图函数,并且将其经过某种处理进行验证
02 表单建立
2.1获取用户名
<form action="/username/" method="post">
<label for="user_name">User name: </label>
<input id="user_name" type="text" name="user_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
2.2使用Django建立表单
在应用目录下新建forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
2.3视图函数对数据验证,views.py
From 类有一个方法is_valid(),来验证是否满足要求
from django.http import HttpResponseRedirect
from django.shortcuts import render
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})
03 模型创建表单
3.1Django提供一个帮助类(ModelForm)可以从一个django模型创建一个Form类
3.2创建Article
>>> 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)
3.3一个完整的例子
from django.db import models
from django.forms import ModelForm
TITLE_CHOICES = (
('MR', 'Mr.'),
('MRS', 'Mrs.'),
('MS', 'Ms.'),
)
class Author(models.Model):
name = models.CharField(max_length=100)
title = models.CharField(max_length=3, choices=TITLE_CHOICES)
birth_date = models.DateField(blank=True, null=True)
def __str__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ['name', 'title', 'birth_date']
class BookForm(ModelForm):
class Meta:
model = Book
fields = ['name', 'authors']