我希望表单只显示ChoiceField中当前用户的帐户。我尝试了以下操作,但它不起作用。
编辑:对不起,我忘了提及我添加的“if kwargs”,因为TransForm()没有显示任何字段。我想这是错的,但我不知道另一种方式。
views.py:
def in(request, account):
if request.method == 'POST':
form = TransForm(request.user, data=request.POST)
if form.is_valid():
...
else:
form = TransForm()
context = {
'TranForm': form,
}
return render_to_response(
'cashflow/in.html',
context,
context_instance = RequestContext(request),
)
forms.py:
class TransForm(ModelForm):
class Meta:
model = Trans
def __init__(self, *args, **kwargs):
super(TransForm, self).__init__(*args, **kwargs)
if kwargs:
self.fields['account'].queryset = Account.objects.filter(user=args[0])
答案 0 :(得分:4)
当请求为NO post请求时,您还需要正确初始化表单:
if request.method == 'POST':
form = TransForm(user=request.user, data=request.POST)
if form.is_valid():
...
else:
form = TransForm(user=request.user)
...
此外我建议在调用超类'构造函数时删除新参数:
class TransForm(ModelForm):
class Meta:
model = Trans
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(TransForm, self).__init__(*args, **kwargs)
self.fields['account'].queryset = Account.objects.filter(user=user)
答案 1 :(得分:1)
在forms.py中尝试此操作:
class TransForm(ModelForm):
class Meta:
model = Trans
def __ini__(self, user, *args, **kwargs):
super(TransForm, self).__init__(*args, **kwargs)
qs = Account.objects.filter(user=user)
self.fields['account'] = ModelChoiceField(queryset=qs)
我假设您已将表单导入为from django.forms import *
。
我不确定究竟是什么导致了你的问题,但我怀疑有两件事(很可能都是):