Different initial data for each form in a Django formset

前端 未结 4 1266
灰色年华
灰色年华 2020-12-07 17:37

Is it possible to prepopulate a formset with different data for each row? I\'d like to put some information in hidden fields from a previous view.

According to the d

4条回答
  •  时光取名叫无心
    2020-12-07 18:30

    You need to use the technique described in this post in order to be able to pass parameters in. Credit to that author for an excellent post. You achieve this in several parts:

    A form aware it is going to pick up additional parameters

    Example from the linked question:

    def __init__(self, *args, **kwargs):
        someeobject = kwargs.pop('someobject')
        super(ServiceForm, self).__init__(*args, **kwargs)
        self.fields["somefield"].queryset = ServiceOption.objects.filter(
                                                               somem2mrel=someobject)
    

    Or you can replace the latter code with

        self.fields["somefield"].initial = someobject
    

    Directly, and it works.

    A curried form initialisation setup:

    formset = formset_factory(Someform, extra=3)
    formset.form = staticmethod(curry(someform, somem2mrel=someobject))
    

    That gets you to passing custom form parameters. Now what you need is:

    A generator to acquire your different initial parameters

    I'm using this:

    def ItemGenerator(Item):
        i = 0
        while i < len(Item):
            yield Item[i]
            i += 1
    

    Now, I can do this:

    iterdefs = ItemGenerator(ListofItems) # pass the different parameters 
                                          # as an object here
    formset.form = staticmethod(curry(someform, somem2mrel=iterdefs.next()))
    

    Hey presto. Each evaluation of the form method is being evaluated in parts passing in an iterated parameter. We can iterate over what we like, so I'm using that fact to iterate over a set of objects and pass the value of each one in as a different initial parameter.

提交回复
热议问题