Django CreateView 簡單使用


django.views.generic中的CreateView類,是基於View的子類。CreateView可以簡單快速的創建表對象。

下面記錄小作代碼。

# polls/views.py

from
django.views.generic import CreateView class QuestionCreate(CreateView): form_class = QuestionForm # 表類 template_name = 'polls/question_form.html' # 添加表對象的模板頁面 success_url = '/polls/thanks' # 成功添加表對象后 跳轉到的頁面 def form_invalid(self, form): # 定義表對象沒有添加失敗后跳轉到的頁面。 return HttpResponse("form is invalid.. this is just an HttpResponse object")
# polls/forms.py 

from
django.forms import ModelForm from polls.models import * class QuestionForm(ModelForm): class Meta: model = Question fields = '__all__'
# polls/models.py

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question_text + '\n' + str(self.pub_date)
# polls/question_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<form method="post">
{% csrf_token %}
{{ form.as_p }}   # {{ form.as_p }}會按QuestionForm中 Meta的fields的列表,列出需要添加的字段。
<input type="submit"  value="Submit" />
</form>

</body>
</html>
# polls/thanks.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Thanks</title>
</head>
<body>
Thanks!
</body>
</html>
# polls/urls.py

from django.conf.urls import url
from . import views

urlpatterns = [

url(r'^questioncreate/$', views.QuestionCreate.as_view(), name='QuestionCreate'),

]

 



QuestionCreate繼承了CreateView, form_class指定了表單QuestionForm, QuestionForm指定了數據表Question, template_name指定了添加表對象的模板, success_url指定了添加表對象成功后跳轉的頁面,
 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM