在Formset中使用时,ModelForm可以接受__init__参数吗?

时间:2014-08-26 10:17:13

标签: python django

是否可以使用ModelForm作为request.user的一部分,在其__init__方法中接受Formset参数?

我有以下ModelFormuser参数__init__

class ExpenditureForm(forms.ModelForm):
    exp_date = forms.DateField(
        widget=AdminDateWidget(attrs={'class':'exp_date_class'}))
    description = forms.CharField(max_length=500)
    amount = forms.FloatField(initial=0)
    currency = forms.CharField(
        widget=forms.TextInput(
            attrs={'class':'currencyClass',}), initial="MYR")
    exp_pocket = forms.ModelChoiceField(
        queryset=Pockets.objects.none(),
        to_field_name="exp_pocket")

    class Meta:
        model = Expenditure

    def __init__(self, user, *args, **kwargs):
        super(ExpenditureForm, self).__init__(*args, **kwargs)
        self.fields['exp_pocket'].queryset = \
            Pockets.objects.filter(pocket_owner=user)

以及以下Formset

ExpFormSet = modelformset_factory(
    Expenditure, extra=10, max_num=10,
    fields=('exp_date', 'description', 'amount', 'currency', 'exp_pocket'),
    can_delete=False)

Expenditure模型是:

class Expenditure(models.Model):
    exp_owner= models.CharField(default='None',max_length=50)
    exp_date = models.DateField("Expenditure_Date")
    description = models.CharField(max_length=500)
    amount = models.FloatField(default=0)
    currency = models.CharField(max_length=15,default="MYR",editable=True)
    exp_pocket = models.ForeignKey(Pockets, null=True, blank=True)

    class Meta:
        unique_together = ('exp_date', 'description',)

1 个答案:

答案 0 :(得分:0)

感谢@Aamir Adnan,他在以下链接中的答案有所帮助:

Limit values in the modelformset field

formset.form.base_fields['exp_pocket'].queryset = Pockets.objects.filter(pocket_owner=request.user)