How to pass in a parameter to the form within the formset?

≯℡__Kan透↙ 提交于 2019-12-10 12:07:38

问题


I would like to create a formset, where each form has a dropdown pointing to a set of sales items.

Model:

class SalesItem(models.Model):        
    item_description    = models.CharField(max_length=40)
    company             = models.ForeignKey(Company)

Here I create a form with a dropdown, hoping to pass in the company as a source for the dropdown. Hold on to this thought, as I think that is not possible in my scenario.

Form:

class SalesItemFSForm(Form):        
    sales_item      =   forms.ModelChoiceField(required=False, queryset = '')

    def __init__(self, company, *args, **kwargs):
        super(SalesItemFSForm, self).__init__(*args, **kwargs)
        self.fields.sales_item.queryset = company.salesitem_set.all()

Now within my view I would like to create a formset with this form:

formset_type = formset_factory(SalesItemFSForm, extra=0)

The problem becomes right away clear, as there seem to be no way that I could pass in the company to determine the source for the dropdown.

How am I supposed to do this?

Many Thanks,

Update:

it seems Jingo cracked it. :)

A ModelForm works better than a Form. On top of it I had to add fields = {} to SalesItemFSForm, to make sure that the SalesItem's fields are not showing up in the template. Because all we are interested in is our dropdown (SalesItem).

So far so good. But now I see as many dropdowns shown as I have Salesitems. It shouldn;t show any unless the user presses a jquery button.

And I think this is the problem, we should NOT pass in

formset_type = modelformset_factory(SalesItem, form=SalesItemFSForm, extra=0)

Because our form doesn't need any instance of the SalesItem. We need a dummy Model.

That was the reason I tried to solve it initially with classic Formset instead of ModelFormset. So its kind of half way there. :)

Update 2:

Jingo, good point. Effectively I was thinking of a custom save, where I just see how many formsets are added by the user via jQuery and save it myself within the view. Literally SalesItem is a ManyToMany field. But the standard M2m widget is horrible. Hence I wanted to replace it with formsets, where each salesItem is a dropdown. The user can then add as many dropdowns (forms in formset) to the page and submit them. Then I would add the relationship in the view.

class DealType(models.Model):    
    deal_name           = models.CharField(_(u"Deal Name"), max_length=40)
    sales_item          = models.ManyToManyField(SalesItem)    
    price               = models.DecimalField(decimal_places=2, max_digits=12)

Hope this makes it clear. Maybe there is an easier way to do this. :)

Btw I also found this excellent jquery snippet code how to add/remove forms to/from a formset.

Update 3:

Indeed when instantiating the object like this, we would only get one form in the formset and can add more via jquery. Perfect!! Unless there is an easier way to achieve this. :)

salesitem_formsets = formset_type(queryset=SalesItem.objects.filter(pk=1))

However this comes back hunting you in the request.POST, since you can't just do:

salesitem_formsets = formset_type(request.POST)

It still requires the queryset to be set. Tricky situation...


回答1:


I hope I understood the goal you want to achieve right. Then maybe you could use ModelForm and its available instance like this:

class SalesItemFSForm(forms.ModelForm):
    class Meta:
        model = SalesItem

    def __init__(self, *args, **kwargs):
        super(SalesItemFSForm, self).__init__(*args, **kwargs)
        self.sale_items = self.instance.company.salesitem_set.all()
        self.fields['sales_item'] = forms.ModelChoiceField(queryset=self.sale_items)

This is untested though and just a thought. I hope this leads into the right direction, but if its totally wrong, let me know and i will remove my answer, so that others wont be confused :).



来源:https://stackoverflow.com/questions/11974924/how-to-pass-in-a-parameter-to-the-form-within-the-formset

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