Passing and using the request object in django forms

I'm trying to user the request object to create a dynamic dropdown list in my form using the following code:

view:

form = TransactionForm(request.user)

form:

class TransactionForm(forms.Form, request.user):
    # Payment methods
    get_mm_details = MMDetails.objects.filter(username=request.user)
    get_card_details = CardDetails.objects.filter(username=request.user)
    payment_meth = []

    # form fields
    trans_amount = forms.IntegerField(label="Amount", min_value=0)
    payment_method = forms.CharField(
        label='Payment method',
        widget=forms.Select(
            choices=payment_meth
            )
    )

is there a way of using the request object in a form?


You are passing request in class inheritance that definitely not the right way. You need to create constructor and pass request there like this:

forms.py:

 class TransactionForm(forms.Form):

   get_mm_details = None
   get_card_details = None
   payment_meth = []

   # rest of the code

   def __init__(self, *args, **kwargs):
     self.request = kwargs.pop('request', None)
     username = self.request.user.username
     self.get_mm_details = MMDetails.objects.filter(username=username)
     self.get_card_details = CardDetails.objects.filter(username=username)
     super(MyForm, self).__init__(*args, **kwargs)

views.py:

 form = TransactionForm(request=request)