Limit Django's inlineformset_factory to only create new objects

前端 未结 3 1114
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 13:41

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)         


        
相关标签:
3条回答
  • 2021-02-04 14:03

    Based on Jeremy Lewis and if you don't want to subclass BaseInlineFormSet, you can just give an empty queryset parameter to your BookFormSet.

    See pseudo (untested) Django 1.6 code sample:

    BookFormSet = inlineformset_factory(parent=Author, model=Book)
    if request.method == "POST":
        formset = BookFormSet(request.POST, request.FILES, instance=author)
        if formset.is_valid():
            formset.save()
    else:
        queryset = Book.objects.none() # does not allow to edit books
        formset = BookFormSet(instance=project, initial=initial, queryset=queryset)
    return render(request, "add_book.html", { "formset": formset, })
    
    0 讨论(0)
  • 2021-02-04 14:09

    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)
    
    0 讨论(0)
  • 2021-02-04 14:14

    Actually the answer is given in the documentation. Just don't give any instance to the FormSet. From the doc:

    >>> from django.forms.models import inlineformset_factory
    >>> BookFormSet = inlineformset_factory(Author, Book)
    >>> author = Author.objects.get(name=u'Mike Royko')
    >>> formset = BookFormSet() # This will create an empty form with your model fields
    

    You can then create view as follows:

    if request.method == "POST":
        formset = BookFormSet(request.POST, request.FILES)
        if formset.is_valid():
            formset.save()
    else:
        formset = BookFormSet()
    return render_to_response("add_book.html", {
        "formset": formset,
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题