gpt4 book ai didi

django - 根据用户限制字​​段的选择

转载 作者:行者123 更新时间:2023-12-02 03:46:39 27 4
gpt4 key购买 nike

我希望表单仅在 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),
)

表单.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])

最佳答案

当请求为NO post请求时,还需要正确初始化表单:

if request.method == 'POST':
form = TransForm(user=request.user, data=request.POST)
if form.is_valid():
...

else:
form = TransForm(user=request.user)
...

此外,我建议在调用父类(super class)的构造函数时删除新参数:

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)

关于django - 根据用户限制字​​段的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4092352/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com