在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))
原文地址:https://www.cnblogs.com/lowmanisbusy/p/9098119.html
时间: 2024-10-05 04:45:08