Empty ModelFormset in Django's FormWizard

陌路散爱 提交于 2019-12-06 04:45:22

问题


I'm using Django's FormWizard. It works fine but I'm having trouble getting any empty model formset to display correctly.

I have a model called Domain. I'm creating a ModelFormset like this:

DomainFormset = modelformset_factory(Domain)

I pass this to the FormWizard like this:

BuyNowWizardView.as_view([DomainFormset])

I don't get any errors but when the wizard renders the page, I get a list of all Domain objects. I'd like to get an empty form. How I can do this? I've read that I can give a queryset parameter to the ModelFormset like Domain.objects.none() but it doesn't seem to work as I get errors.

Any ideas on where I'm going wrong?

Thanks


回答1:


The Django docs give two ways to change the queryset for a formset.

The first way is to pass the queryset as an argument when instantiating the formset. With the formwizard, you can do this by passing instance_dict

# set the queryset for step '0' of the formset
instance_dict = {'0': Domain.objects.none()}

# in your url patterns
url(r'^$', BuyNowWizardView.as_view([UserFormSet], instance_dict=instance_dict)),

The second approach is to subclass BaseModelFormSet and override the __init__ method to use the empty queryset.

from django.forms.models import BaseModelFormSet

class BaseDomainFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseDomainFormSet, self).__init__(*args, **kwargs)
        self.queryset = Domain.objects.none()

DomainFormSet = modelformset_factory(Domain, formset=BaseDomainFormSet)

You then pass DomainFormSet to the form wizard as before.



来源:https://stackoverflow.com/questions/8316145/empty-modelformset-in-djangos-formwizard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!