gandalf129875
gandalf129875

Reputation: 97

How to delete model objects using an inline formset in Django

In Django I am trying to use an inline formset factory so a user can edit and delete instances of a model related to a parent model via a foreignkey. For some reason the methods I am trying allow me to edit the objects, but when I click the delete checkbox the object doesn't delete. It is not showing me any error messages either, even when I use formset.errors or formset.non_form_errors.

Models:

class ExerciseName(models.Model):
    muscle_group = models.ForeignKey(MuscleGroup, on_delete = models.CASCADE)
    name_of_exercise = models.CharField(max_length=100, default = 'Exercise name', unique=True)


    def __str__(self):
        return self.name_of_exercise


class SetLogger(models.Model):

    weight = models.IntegerField(default=0)
    reps = models.IntegerField(default=0)
    date = models.DateField(default=datetime.date.today)
    exercisegroup = models.ForeignKey(ExerciseName, on_delete = models.CASCADE)

Content within the view I am using (not including render):

    exercisename = ExerciseName.objects.get(pk=exercisegroup_id)
    SetsFormSet = inlineformset_factory(ExerciseName, SetLogger, fields=('weight','reps',), can_delete=True)

    formset = SetsFormSet(instance=exercisename)

    sets = SetLogger.objects.filter(exercisegroup=exercisename)

    if request.method == 'POST':  
      formset = SetsFormSet(request.POST, instance=exercisename)
      for form in formset:
        if form.is_valid():
           form = form.save(commit=True)
      else:
        formset = SetsFormSet(instance=exercisename)

And I am displaying the forms in my formset like this:

<form method="post">{% csrf_token %}
               {{ formset.management_form }}
               <table>
                  {% for form in formset %}
                        {{ form }}
                  {% endfor %}
               </table>
               <button type="submit" class="save btn btn-default">Save set</button>
          </form>

This code shows a delete checkbox next to each form and each form saves if I change its data, but not if I select 'delete'. Am I missing something I should be doing differently?

Upvotes: 2

Views: 3097

Answers (1)

nigel222
nigel222

Reputation: 8212

You aren't using formset.save(commit=True). I'm pretty certain that if you iterate over the forms instead, you only get the changed ones, not the deleted ones. For those, you need

for obj in formset.deleted_objects:
    obj.delete()  
    # or the possibility of using that checkbox to select these for other special treatment

Upvotes: 4

Related Questions