根据用户限制字​​段的选择 [英] Limit the choices of a field based on a user

查看:65
本文介绍了根据用户限制字​​段的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望表单仅在ChoiceField中显示当前用户的帐户。我尝试执行以下操作,但不起作用。

I'd like the form to only show the accounts of the current user in the ChoiceField. I tried doing the following but it doesn't work.

编辑:对不起,我忘记提及由于TransForm()而添加的 if kwargs了不显示任何字段。我想这是错误的,但我不知道其他方法。

Sorry, I've forgot to mention the "if kwargs" I added because of the TransForm() not showing any fields. I guess this is wrong but I don't know another way.

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])


推荐答案

当请求为非请求后,您还需要正确初始化表单:

You also need to initialize the form correctly when the request is NO post request:

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

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

此外,我建议在调用超类的构造函数时删除新参数:

and furthermore I'd recommend to remove the new argument when calling the superclass' constructor:

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)

这篇关于根据用户限制字​​段的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆