django form 介绍

django form 介绍


Get,Post使用方法

GET and POST are the only HTTP methods to use when dealing with forms.

使用Get方法,请求报文实体主体为空,Post方法时,用户在表单字段中输入的内容即为实体主体。
Get的方法可在请求的URL中包括输入的数据,如“www.somesite.com/animalsearch?monkeys&bananas”

Any request that could be used to change the state of the system - for example, a request that makes changes in the database - should use POST. GET should be used only for requests that do not affect the state of the system.
GET is suitable for things like a web search form, because the URLs that represent a GET request can easily be bookmarked

The Django Form class

a form class’s fields map to HTML form<input>elements

form运用

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

一个field对应一个<label>
Form实例含有is_vaild()方法
它确保表单中的数据正确无误,并将其置入cleaned_date

发送来的表单数据由view处理,例如

	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})

django设计了一种方法来避免重复代码
假如forms.py中代码如下

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField()
    message = forms.CharField(widget=forms.Textarea)

    def send_email(self):
        # send email using the self.cleaned_data dictionary
        pass

view中代代码可改写如下

from myapp.forms import ContactForm
from django.views.generic.edit import FormView

class ContactView(FormView):
    template_name = 'contact.html'
    form_class = ContactForm
    success_url = '/thanks/'

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        form.send_email()
        return super(ContactView, self).form_valid(form)

引用

Form handling with class-based views
Working with forms

posted @ 2016-04-09 15:31  匣中失乐  阅读(240)  评论(0编辑  收藏  举报