我对此很陌生,所以请耐心等待。我创建了一个“编辑书籍”表单,modelformset_factory
用于使用 Book 模型构建表单。当我使用模型中的数据加载表单并尝试保存它时,无论我是否以任何方式更改表单中的数据,is_valid()
总是返回 False。
代码:
模型.py
class Book(models.Model):
def __unicode__(self):
return self.title
user = models.ForeignKey(User)
title = models.CharField(max_length=300)
author = models.CharField(max_length=200)
description = models.TextField(blank=True)
pub_date = models.DateField(blank=True, null=True)
link = models.URLField(blank=True, null=True)
category = models.CharField(max_length=2, choices=CATEGORY_CHOICES)
rating = models.IntegerField(blank=True, null=True, default=0)
date_added = models.DateField(auto_now_add=True)
date_reading = models.DateField(blank=True, null=True)
date_read = models.DateField(blank=True, null=True)
notes = models.TextField(blank=True, null=True)
reading = models.BooleanField(default=False)
book_read = models.BooleanField(default=False)
视图.py
from django.forms.models import modelformset_factory
from models import Book
def edit_book(request, book_id):
BookFormSet = modelformset_factory(Book, exclude=('user', 'date_reading', 'date_read', 'reading', 'book_read'), max_num=1)
if request.method == 'POST':
formset = BookFormSet(queryset=Book.objects.filter(pk=book_id))
if formset.is_valid():
formset.save()
return redirect('/books/' + str(book_id))
else:
formset = BookFormSet(queryset=Book.objects.filter(pk=book_id))
return render(request, 'books/edit.html', {'formset':formset})
补充说明:
formset.is_bound 返回 False
formset.errors 返回 []
formset.non_form_errors() 不返回任何内容
formset.has_changed() 返回 True