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 + '
' + 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指定了添加表对象成功后跳转的页面,

原文地址:https://www.cnblogs.com/haoshine/p/5649344.html