I have the following Django models:
class Order:
order_id
order_date
class OrderItem
models.ForeignKey(Order)
models.ForeignKey(Product)
quantity
unit_price
To explain, an order can contain multiple order items.
Now, I want to create a template which would allow the creation of an order. So in my view function I have the following:
def new_order:
order = Order()
OrderItemFormSet = inlineformset_factory(Order, OrderItem, extra=2)
formset = OrderItemFormSet()
cntx = {'formset': formset, 'order':order}
return render_to_response('some_page.html', cntx)
In the template itself, I iterate over the forms in the formset and all seems to work meaning I am able to create an order with multiple order items.
Now, I have created a new model called Product. The new Product model will be part of the OrderItem model. So we order item contains a product along with other metrics like quantity, unit price etc.
class Product:
product_code
product_name
Next, I updated the OrderItem model with the following line:
product = models.ForeignKey(Product)
开发者_JS百科
The problem I am facing is how to handle the above scenario in the template. Before adding the Product model, the for loop which iterates over the formset is like this:
{% for form in formset %}
<td> {{form.quantity}} </td>
....
{%endfor%}
Now, ideally, I thought I could this:
{% for form in formset %}
<td> {{form.quantity}} </td>
<td> {{form.product.code}} </td>
....
But the above does not work. Basically, what I want to achieve is to be able to add the product code while creating the order items for an order. Upon save, the order item should be saved with the corresponding product id of the product code entered by the user.
Any insight will be appreciated.
Thanks...
You can't have multiply nested formsets. But you don't need them here. All you really want is for the orderitem form to have a product
field, which is a select box of all the available products and their codes. And you get that automatically, as long as you define the __unicode__
method of the Product model to return the product code, and then use form.product
in the template.
精彩评论