1

Is it possible to use a ModelForm, that accepts a request.user parameter in it's __init__ method, as part of a Formset?

I have the following ModelForm that has a user parameter in it's __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)

and the following Formset:

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

The Expenditure model is:

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',)
John Keyes
  • 5,479
  • 1
  • 29
  • 48
paarth batra
  • 1,392
  • 4
  • 29
  • 53
  • This might help you... http://stackoverflow.com/questions/5426031/django-formset-set-current-user – nKandel Aug 26 '14 at 10:41

1 Answers1

0

Thank to @Aamir Adnan his answer in below link helped :

Limit values in the modelformset field

formset.form.base_fields['exp_pocket'].queryset = Pockets.objects.filter(pocket_owner=request.user)
Community
  • 1
  • 1
paarth batra
  • 1,392
  • 4
  • 29
  • 53