Reputation: 11
what does it do in this function, what does it mean generally?
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order, fields = ('product','status'), extra=10)
customer=Customer.objects.get(id=pk)
formset=OrderFormSet(queryset=Order.objects.none(),instance=customer)
if request.method=='POST':
formset=OrderFormSet(request.POST,instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context={'formset':formset}
return render(request, 'accounts/order_form2.html',context)
Upvotes: 0
Views: 637
Reputation: 11424
inlineformset_factory
creates a formset for model objects that belong to a certain other model object. The first argument is parent_model
which is the class of the "parent" model (the one to which the others must belong). The second argument is model
- the model class for which the forms will be created.
With inlineformset_factory(Customer, Order,...
you are creating a formset that can create forms for Order
s that belong to a certain Customer
.
The way you can specify which specific Customer
all the Order
s must belong to is by passing the instance
argument to the formset. An example is given under Inline formsets in the docs.
The queryset
argument allows you to limit for which objects in the model to create a form for. In your case, for which Order
s a form should be displayed. An example is given under Changing the queryset in the docs. By default queryset
is set to all of the objects in the model, e.g. Order.objects.all()
.
Order.objects.none()
selects an empty queryset. Setting queryset
to an empty queryset will mean that no forms will be displayed for existing Order
s. Only a form for a new Order
will be displayed.
With OrderFormSet(queryset=Order.objects.none(),instance=customer)
like you have above, you're essentially saying: create a form for a new Order
object which should be linked to customer
.
Upvotes: 1