限制Django的inlineformset_factory仅创建新对象 [英] Limit Django's inlineformset_factory to only create new objects
问题描述
author = Author.objects.get(pk = 1)
BookFormSet = inlineformset_factory(作者,书)
formset = BookFormSet(request.POST,instance = author)
将创建一个内联表单来编辑特定作者的书籍。
我想创建一个只允许用户添加新书的表单集作者,不编辑现有的书籍。有没有一种简单的方法来使用inlineformset_factory来做到这一点?
inlineformset_factory采用一个formset kwarg,默认为BaseInlineFormSet。 BaseInlineFormSet子类BaseModelFormSet,它定义了get_queryset方法。如果创建一个BaseInlineFormSet子类并覆盖get_queryset来返回EmptyQuerySet(),那么你应该得到你以后的内容。在上面的例子中,它将如下所示:
from django.db.models.query import EmptyQuerySet
从django.forms.models导入BaseInlineFormSet
class BaseInlineAddOnlyFormSet(BaseInlineFormSet):
def get_queryset(self):
return EmptyQuerySet()
author = Author.objects.get(pk = 1)
BookFormSet = inlineformset_factory(作者,Book,formset = BaseInlineAddOnlyFormSet)
formset = BookFormSet(request.POST,instance = author)
I am using django's inline formset factory. To use the example in the docs,
author = Author.objects.get(pk=1)
BookFormSet = inlineformset_factory(Author, Book)
formset = BookFormSet(request.POST, instance=author)
will create an inline formset to edit books by a particular author.
I want to create a formset that only allows users to add new books by that author, not edit existing books. Is there a simple way to use inlineformset_factory to do this?
inlineformset_factory takes a formset kwarg, which defaults to BaseInlineFormSet. BaseInlineFormSet subclasses BaseModelFormSet, which defines a get_queryset method. If you create a BaseInlineFormSet subclass and override get_queryset to return EmptyQuerySet(), you should get what you're after. In the above example then, it would look like this:
from django.db.models.query import EmptyQuerySet
from django.forms.models import BaseInlineFormSet
class BaseInlineAddOnlyFormSet(BaseInlineFormSet):
def get_queryset(self):
return EmptyQuerySet()
author = Author.objects.get(pk=1)
BookFormSet = inlineformset_factory(Author, Book, formset=BaseInlineAddOnlyFormSet)
formset = BookFormSet(request.POST, instance=author)
这篇关于限制Django的inlineformset_factory仅创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!