我对此很新,所以请耐心等待。
我使用modelformset_factory
创建了一个“编辑书”表单,以使用Book模型构建表单。当我使用模型中的数据加载表单并尝试保存它时,无论我是否以任何方式更改表单中的数据is_valid()
总是返回False。
代码:
models.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)
views.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