zoukankan      html  css  js  c++  java
  • 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指定了添加表对象成功后跳转的页面,
    
    
  • 相关阅读:
    sqlserver获取当前id的前一条数据和后一条数据
    C#实现测量程序运行时间及cpu使用时间
    类库dll引用不成功问题
    合并相同字段
    Android之来历
    XML and JSON 验证
    特殊符号
    git 使用
    格式化字符串:金额
    grunt + sass 使用记录
  • 原文地址:https://www.cnblogs.com/haoshine/p/5649344.html
Copyright © 2011-2022 走看看