想要使用 __init__ 方法让登录用户(客户)过滤 Django From 下拉列表

想要使用方法让登录用户(客户)过滤 Django From 下拉列表__init__。但是当提交表单时,继续让这个 Field idexpected a number 但得到 <QueryDict: { error:


class OrderForm(ModelForm):



    class Meta:

        model = Order

        fields = ['contract', 'quantity', 'status']

        

    

    def __init__(self, customer, *args, **kwargs):

        super(OrderForm, self).__init__(*args, **kwargs)

        self.fields['contract'].queryset = Contract.objects.filter(customer=customer)

    



@login_required(login_url='login')

def createOrder(request):


    customer = request.user.customer.id


    form = OrderForm(customer)


    if request.method == 'POST':

        form = OrderForm(request.POST)

        if form.is_valid():

            form = form.save(commit=False)

            form.customer = request.user.customer

            form.save()

            messages.success(request, 'Ticket submitted successfully .')

            return redirect('customer_table')


    context = {'form':form}


    return render(request, 'create-order.html', context)


PIPIONE
浏览 90回答 2
2回答

慕容708150

您可以像这样以形式传递任何属性在视图中:&nbsp; &nbsp;form = OrderForm(request.POST, customer=request.user)通知:&nbsp; def __init__(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; customer = kwargs.pop('user') # allway before super()&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# and call .pop() not .get() on kwargs, for upper class not evaluate user keyword&nbsp; &nbsp; &nbsp; &nbsp; super(OrderForm, self).__init__(*args, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; self.fields['contract'].queryset = Contract.objects.filter(customer=customer)

扬帆大鱼

我将工作解决方案总结如下:View.pydef createOrder(请求):form = OrderForm(request.POST, customer=request.user.customer.id)if request.method == 'POST':&nbsp; &nbsp; form = OrderForm(request.POST, customer=request.user.customer.id)&nbsp; &nbsp; if form.is_valid():&nbsp; &nbsp; &nbsp; &nbsp; form = form.save(commit=False)&nbsp; &nbsp; &nbsp; &nbsp; form.customer = request.user.customer&nbsp; &nbsp; &nbsp; &nbsp; form.save()&nbsp; &nbsp; &nbsp; &nbsp; messages.success(request, 'Ticket submitted successfully .')&nbsp; &nbsp; &nbsp; &nbsp; return redirect('customer_table')context = {'form':form}return render(request, 'create-order.html', context)类 OrderForm(ModelForm):class Meta:&nbsp; &nbsp; model = Order&nbsp; &nbsp; fields = ['contract', 'quantity', 'status']def __init__(self, *args, **kwargs):&nbsp; &nbsp; customer = kwargs.pop('customer')&nbsp; &nbsp; super(OrderForm, self).__init__(*args, **kwargs)&nbsp; &nbsp; self.fields['contract'].queryset = Contract.objects.filter(customer__id=customer)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python