InlineFormFactory Column' book_id'不能为空

时间:2014-07-25 10:52:42

标签: python django

好的我正在做测试。我想上传一些pdf文件。所以我按照formset教程

但似乎有一个错误即将来临

(1048, "Column 'book_id' cannot be null") 

这是模型类。

class Book(models.Model):
     author = models.ForeignKey(Author)#,  null=True, blank=True)
     album_name = models.CharField(max_length=100)
     created_on = models.DateTimeField(default=datetime.datetime.now)

class Book_File(models.Model):
     filefile = models.FileField(upload_to=content_file_name)
     book = models.ForeignKey(Book)#,  null=True, blank=True)

ModelForm看起来很

class BookForm(ModelForm):
    class Meta:
        model = Book_File
        fields = ['filefile', 'book']

BookFormSet = inlineformset_factory(Book, Book_File, extra=3, can_delete=False)
book = Book.objects.get(book_name=u'New')
formset = AlbumFormSet(instance=book)

如果我按照django教程中的建议把book_id放在viewal中,那么错误就会出现

def viewalbum(request,book_id):
    book = Book.objects.get(pk=book_id)
    if request.method == 'POST':
        formset = BookFormSet(request.POST, request.FILES, instance=book)
        if formset.is_valid():
            for data in formset.cleaned_data:
                Book_File.objects.create(filefile=data['filefile'])
            return HttpResponseRedirect(reverse('first.views.viewalbum'))
    else:
        formset = BookFormSet(instance=book)
    return render_to_response('test.html',{'formset': formset})

告诉我我错过了什么?

1 个答案:

答案 0 :(得分:0)

您将数据保存为

if formset.is_valid():
    for data in formset.cleaned_data:
        Book_File.objects.create(filefile=data['filefile'])

您在此处创建Book_File对象,但未指定book实例。你应该做

if formset.is_valid():
    for data in formset.cleaned_data:
        Book_File.objects.create(filefile=data['filefile'], book=book)

或者只是做

if formset.is_valid():
    formset.save()