5

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

Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382

1 Answers1

6

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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Hey Alasdair, I've tried the method you mentioned and I still get form fields with the data filled in. I'm wondering if this is a bug. The only difference from the regular form wizard that I'm using the newer one from Django 1.4 which has been backported to DJango 1.3 https://github.com/stephrdev/django-formwizard – Mridang Agarwalla Nov 29 '11 at 19:40
  • What do you mean by *filled in*? Is it displaying existing domains from the database, or just pre-filling the forms with `initial` data? – Alasdair Nov 29 '11 at 19:44
  • 2
    Yes, it is displaying all the existing domains from the database. I get one form for each `Domain` record with the values in it. – Mridang Agarwalla Nov 29 '11 at 19:50
  • Hmm. I made a test project (Django trunk, 1.4 pre-alpha), and the subclassing method does not work for me either. I have updated my answer with the `instance_dict` approach, which **does** work for me. – Alasdair Nov 29 '11 at 21:22