zoukankan      html  css  js  c++  java
  • 利用django form 模块处理post请求

    在django框架中,利用 form 模块处理post请求提交的数据,可以大大提高开发效率,减小代码冗余度,提高性能

    models.py 中:

    from django.db import models
    
    TITLE_CHOICES = (
        ('MR', 'Mr.'),
        ('MRS', 'Mrs.'),
        ('MS', 'Ms.'),
    )
    
    class Author(models.Model):
        name = models.CharField(max_length=100)
        title = models.CharField(max_length=3, choices=TITLE_CHOICES)
        birth_date = models.DateField(blank=True, null=True)
    
        def __unicode__(self):
            return self.name
    
    class Book(models.Model):
        name = models.CharField(max_length=100)
        authors = models.ManyToManyField(Author)

    自定义的form.py文件

    
    
    from django.forms import ModelForm

    class
    AuthorForm(ModelForm): class Meta:
         # 绑定模型 model
    = Author
         # 忽略该字段,将其排除出处理范围之内
         exclude = ('birth_date',)
    class BookForm(ModelForm): class Meta:
         # 绑定模型 model
    = Book

    views.py中

    def testModelForm(request):
    #    a=Author.objects.get(pk=1)
    #    form=AuthorForm(instance=a)
        form=AuthorForm()
        if request.method=='POST':
            form=AuthorForm(request.POST)
         # 如果创建form对象成功,则将数据保存
    if form.is_valid(): form.save() return HttpResponseRedirect(reverse('welcome')) return render_to_response('testModelForm.html',locals(),RequestContext(request))
  • 相关阅读:
    开学考试学生成绩管理Java
    动手动脑问题1
    数据库的链接错误分析
    ASP.NET自定义错误页面
    php declare
    HTTP运行期与页面执行模型
    分部类(Partial Classes)
    ASP.NET:小编浅谈泛型的使用
    Windows 2003 SP2下安装IIS无法复制文件
    php 的include require 区别
  • 原文地址:https://www.cnblogs.com/lowmanisbusy/p/9098119.html
Copyright © 2011-2022 走看看