To accomplish what you described in Django, we have to approach this in steps, considering the dynamic nature of adding multiple items (products) to an order on a single form. We will be dealing with Django Forms and Django Formsets along with some JavaScript for dynamically adding more products to the order.
- First, let's create a form for the
Order. This form will include fields for date and invoice.
forms.py
from django import forms
from .models import Order, OrderItem, Product
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['date', 'invoice']
- Next, create a form for
OrderItem. This form will include a dropdown for products and a field for count.
class OrderItemForm(forms.ModelForm):
product = forms.ModelChoiceField(queryset=Product.objects.all())
count = forms.IntegerField(min_value=1)
class Meta:
model = OrderItem
fields = ['product', 'count']
- Now, we utilize Django's formsets to handle multiple
OrderItems in one go. You'll need to create an OrderItemFormSet using Django's inline formset factory.
from django.forms import inlineformset_factory
OrderItemFormSet = inlineformset_factory(Order, OrderItem, form=OrderItemForm, extra=1)
- In your view, you'll handle both the order form and the order item formset. Upon POST request, you'll save the order first and then the order items.
views.py
from django.shortcuts import render, redirect
from django.urls import reverse
from .forms import OrderForm, OrderItemFormSet
def add_order_with_items(request):
if request.method == 'POST':
form = OrderForm(request.POST)
formset = OrderItemFormSet(request.POST)
if form.is_valid() and formset.is_valid():
order = form.save()
formset.instance = order
formset.save()
return redirect(reverse('some_view_name'))
else:
form = OrderForm()
formset = OrderItemFormSet()
return render(request, 'your_template_name.html', {'form': form, 'formset': formset})
- To dynamically add more products to the order on the form, you'll need to add a bit of JavaScript to your HTML template. Here's an example leveraging jQuery for simplicity.
your_template_name.html
<form method="post">{% csrf_token %}
{{ form.as_p }}
{{ formset.management_form }}
<div id="items">
{% for form in formset %}
<div class="item-form">{{ form.as_p }}</div>
{% endfor %}
</div>
<button type="button" id="add-more">Add More</button>
<input type="submit">
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$('#add-more').click(function() {
var form_idx = $('#id_form-TOTAL_FORMS').val();
$('#items').append($('#items .item-form:last').clone());
$('#items .item-form:last *').each(function() {
var name = $(this).attr('name').replace('-' + (form_idx-1) + '-', '-' + form_idx + '-');
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('');
});
$('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
Note that this JavaScript code snippet directly manipulates the DOM to clone the last product form, increments the name and id to match the Django formset management, and then appends it to the list. Adjustments may be needed based on your exact setup, and more complex scenarios may require a more robust JavaScript approach.
Lastly, always remember to include jQuery in your base template or wherever you feel it's necessary according to the script reference if you decide to use the jQuery dependent JavaScript code above.