Django - 如何排除表单字段视图?

时间:2015-08-11 03:08:06

标签: python django forms views

如果用户具有特定属性,则排除字段时出现问题。

我尝试使用this tip之后的is_staff选项进行测试,但我无法使其正常运行。我收到错误:__init__() got an unexpected keyword argument 'user'

如果用户是员工,有人可以告诉我如何排除某些字段吗?

这是我在forms.py中的表单

class NewOrderForm(forms.ModelForm):

    class Meta:
        model = WorkOrder
        fields = ['store_internal_order',
                  'sector',
                  'article',
                  'serial',
                  'work',
                  'article_details',
                  'cash_advance',
                  'initial_price'
                  ]

    def __init__(self, *args, **kwargs):
        super(NewOrderForm, self).__init__(*args, **kwargs)
        user = kwargs.pop('user')
        if user.is_staff:
           del self.fields['store_internal_order']

这是我的观点

def new(request):
    if not request.user.is_authenticated():
        return redirect('auth_login')

    title = "Nueva Orden de trabajo"
    store = request.user.userprofile.fk_store
    form = NewOrderForm(request.POST or None)
    context = {"title": title,
               "form": form}

    if 'dni_cuit' in request.session:
        dni_cuit = request.session.get('dni_cuit')
        if Client.objects.get(dni_cuit=dni_cuit):
            dni_cuit = request.session.pop('dni_cuit')
            client = Client.objects.get(dni_cuit=dni_cuit)

            context.update({'client': client})
            request.session['dni_cuit'] = dni_cuit
        else:
            return redirect('new_client')

    # Si el formulario es valido guardamos el contenido
    if form.is_valid():
...
...
...

非常感谢谁能帮助我。

抱歉我的英文不好!

2 个答案:

答案 0 :(得分:3)

您走在正确的轨道上,但您的陈述user = kwargs.pop('user')处于错误的位置。它应该在super(NewOrderForm, self).__init__(*args, **kwargs)之前调用。发生此错误的原因是因为在基本表单类中,__init__()方法并不期望接受您的user参数。因此,我们需要先将其弹出并将其存储在变量中,然后调用super

纠正后:

class NewOrderForm(forms.ModelForm):

    class Meta:
        model = WorkOrder
        fields = ['store_internal_order',
                  'sector',
                  'article',
                  'serial',
                  'work',
                  'article_details',
                  'cash_advance',
                  'initial_price'
                  ]

    def __init__(self, *args, **kwargs):
        # user should be popped here
        user = kwargs.pop('user', None)
        super(NewOrderForm, self).__init__(*args, **kwargs)
        # just in case your user is empty
        if user and user.is_staff:
           del self.fields['store_internal_order']

答案 1 :(得分:0)

不确定是否有任何帮助,但user = kwargs.pop('user')应该user = kwargs.pop('user', None)?您是否也尝试将user=request.user作为NewOrderForm中的参数传递?