Добавление и удаление кнопок при использовании набора форм

Я использую django formsets вместе с формой. enter image description here

При отправке все работает нормально. Я хочу добавить кнопку "Добавить новый" и "Удалить" для полей набора форм.

Мой код выглядит следующим образом:

Views.py:

def create_food_menu(request):

  restaurant = Restaurant.objects.get(id=request.user.restaurant.id)
  form = FoodMenuForm(restaurant)
  FoodMenuPortionFormset = modelformset_factory(FoodMenuPortion,
                                              form=FoodMenuPortionForm,
                                              extra=1)
  food_menu_portion_formset = 
   FoodMenuPortionFormset(queryset=FoodMenuPortion.objects.none(),
                                                   prefix="food_menu_portion_formset"
                                                   )

  if request.method == 'POST':
    form = FoodMenuForm(restaurant, request.POST, request.FILES)
    food_menu_portion_formset = FoodMenuPortionFormset(request.POST, 
    prefix="food_menu_portion_formset")

    if form.is_valid() and food_menu_portion_formset.is_valid():
        food_menu = form.save()
        food_menu.restaurant = restaurant
        unique_filename = image_converter(request.POST.get("imagebase64"), 'food_menu/image/')
        food_menu.image = unique_filename
        food_menu.save()
        for item in food_menu_portion_formset:
            food_menu_portion_obj = item.save(commit=False)
            food_menu_portion_obj.food_menu = food_menu
            food_menu_portion_obj.save()
            addons = item.cleaned_data['addons']
            for addon in addons:
                food_menu_portion_obj.addons.add(addon)
            food_menu_portion_obj.save()
        messages.success(request, 'Food Item Added Successfully.')
        return redirect('list_food_menu')

    else:
        pass
context = {
    "title": "add food item",
    'food_menu_form': form,
    "food_menu_portion_formset": food_menu_portion_formset
}
return render(request, "food_menu/food_menu.html", context)

models.py:

class FoodMenu(models.Model):
  name = models.CharField(max_length=20)
  menu_sub_category = models.ForeignKey(MenuSubCategory, on_delete=models.CASCADE)
  logo = models.ImageField(upload_to='food_menu/logo')
  image = models.ImageField(upload_to='food_menu/image', default='main/default.jpg')
  vegetarian = models.BooleanField(default=True)
  restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True, 
  blank=True)
  price = models.DecimalField(max_digits=10, decimal_places=2)
  availability = models.BooleanField(default=False)
  description = models.TextField(max_length=500, blank=True, null=True)

  class Meta:
    db_table = TABLE_PREFIX + "food_menu"

  def __str__(self):
    return self.name

class FoodMenuPortion(models.Model):
  unit = models.CharField(max_length=20)
  food_menu = models.ForeignKey(FoodMenu, on_delete=models.CASCADE, 
  related_name='food_menu_portion')
  price = models.DecimalField(max_digits=10, decimal_places=2)
  tax = models.DecimalField(max_digits=10, decimal_places=2)
  available_from = models.TimeField(null=True, blank=True)
  available_to = models.TimeField(null=True, blank=True)
  addons = models.ManyToManyField(Addons)

  class Meta:
    db_table = TABLE_PREFIX + "food_menu_portion"

  def __str__(self):
    return self.unit

forms.py:

class FoodMenuForm(forms.ModelForm):

  menu_sub_category = forms.ModelChoiceField(queryset=MenuSubCategory.objects.all())
  menu_sub_category.widget.attrs.update({'class': 'input-group custom-select form- 
  control', 'style': 'width: 100%'})

  def __init__(self, restaurant, *args, **kwargs):
    super(FoodMenuForm, self).__init__(*args, **kwargs)
    self.fields['menu_sub_category'].queryset = 
    MenuSubCategory.objects.filter(restaurant=restaurant)

  class Meta:
    model = FoodMenu
    fields = '__all__'
    exclude = ['restaurant', 'image']

class FoodMenuPortionForm(forms.ModelForm):

  addons = forms.ModelMultipleChoiceField(queryset=Addons.objects.all())
  addons.widget.attrs.update({'class': 'js-select2 form-control input-group',
                            'data - placeholder': 'Choose many..',
                            'style': 'width: 25%; border: 1px solid #d8dfed;',
                            'placeholder': 'Select Addons'
                            })

  class Meta:
    model = FoodMenuPortion
    exclude = ['food_menu']

template:

 <div class="tab-pane" id="wizard-progress-step3" role="tabpanel">
     {% for form in food_menu_portion_formset %}
     <div>
         {{form.id}}
         <div class="row">
             {{form.unit}}
             {{form.price}}
             {{form.tax}}
             {{form.available_from}}
             {{form.available_to}}
             {{form.addons}}
         </div>
     </div>

   {% endfor %}
   {{ food_menu_portion_formset.management_form }}
 </div>

Помогите, пожалуйста, как лучше добавить кнопку добавления и удаления для заполненного набора форм. Спасибо

Вернуться на верх