将URL pk传递给Django modelform(django 1.4)

时间:2019-03-18 06:37:58

标签: python django forms modelform

我想在具有2个外键的modelform中传递url pk,然后将其作为字段查询集上的过滤器。我该怎么办?

class myForm(forms.ModelForm):

    def __init__(self,*args, **kwargs):
    super(OrderReceivingForm, self).__init__(*args, **kwargs)
    for field in self.fields:
        self.fields['field1'].queryset = myModel1.objects.filter(Order=pk)
        self.fields['field2'].queryset = myModel2.objects.filter(Order=pk)

这是我的观点

def order(request,pk):


    myFormSet = modelformset_factory(OrderModel, form=myForm,))

    if request.method == 'POST':
        forms = myFormSet (request.POST)
        if forms.is_valid():
            for form in forms:
                order = form.save(commit=False)
                order.save()
            return HttpResponseRedirect('/foo/')

    form = myFormSet (queryset=OrderModel.objects.None())

    return render(request, 'foo/order.html', {'form': form})

这是我的网址

url (r'^foo/(?P<pk>[\w-]+)/', views.order),

先谢谢您。

0 个答案:

没有答案