當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Django FormView用法及代碼示例


本文介紹 django.views.generic.edit.FormView 的用法。

聲明

class django.views.generic.edit.FormView

顯示表單的視圖。出錯時,重新顯示帶有驗證錯誤的表單;成功後,重定向到一個新的 URL。

祖先 (MRO)

此視圖從以下視圖繼承方法和屬性:

示例 myapp/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

示例 myapp/views.py

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

class ContactFormView(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().form_valid(form)

示例 myapp/contact.html

<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Send message">
</form>

相關用法


注:本文由純淨天空篩選整理自djangoproject.com大神的英文原創作品 django.views.generic.edit.FormView。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。