2 回答
TA贡献1831条经验 获得超4个赞
您可以像这样以形式传递任何属性
在视图中:
form = OrderForm(request.POST, customer=request.user)
通知:
def __init__(self, *args, **kwargs):
customer = kwargs.pop('user') # allway before super()
# and call .pop() not .get() on kwargs, for upper class not evaluate user keyword
super(OrderForm, self).__init__(*args, **kwargs)
self.fields['contract'].queryset = Contract.objects.filter(customer=customer)
TA贡献1799条经验 获得超9个赞
我将工作解决方案总结如下:
View.py
def createOrder(请求):
form = OrderForm(request.POST, customer=request.user.customer.id)
if request.method == 'POST':
form = OrderForm(request.POST, customer=request.user.customer.id)
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)
类 OrderForm(ModelForm):
class Meta:
model = Order
fields = ['contract', 'quantity', 'status']
def __init__(self, *args, **kwargs):
customer = kwargs.pop('customer')
super(OrderForm, self).__init__(*args, **kwargs)
self.fields['contract'].queryset = Contract.objects.filter(customer__id=customer)
添加回答
举报