是否可以使用ModelForm
作为request.user
的一部分,在其__init__
方法中接受Formset
参数?
我有以下ModelForm
个user
参数__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',)
答案 0 :(得分:0)
感谢@Aamir Adnan,他在以下链接中的答案有所帮助:
Limit values in the modelformset field
formset.form.base_fields['exp_pocket'].queryset = Pockets.objects.filter(pocket_owner=request.user)