在 Django 表单中传递和使用请求对象
Passing and using the request object in django forms
我正在尝试使用请求对象在我的表单中使用以下代码创建动态下拉列表:
查看:
form = TransactionForm(request.user)
形式:
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
)
)
有没有办法在表单中使用请求对象?
您在 class 继承中传递请求,这绝对不是正确的方式。您需要像这样创建构造函数并在那里传递请求:
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)
我正在尝试使用请求对象在我的表单中使用以下代码创建动态下拉列表:
查看:
form = TransactionForm(request.user)
形式:
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
)
)
有没有办法在表单中使用请求对象?
您在 class 继承中传递请求,这绝对不是正确的方式。您需要像这样创建构造函数并在那里传递请求:
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)