简体   繁体   中英

How to edit model objects in an inline formset in Django

In Django I am trying to use an inline formset factory so a user can edit instances of a model related to a parent model via a foreignkey. For some reason the methods I am trying don't save the changes I make when I click submit.

My view is like this (not including render):

def edit_sets(request, exercisegroup_id):


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

    formset = SetLoggerFormSet(instance=exercisename)


    if request.method == 'POST':  
      formset = SetLoggerFormSet(request.POST, instance=exercisename)
      if formset.is_valid():
         formset.save()
      else:
        formset = SetLoggerFormSet(instance=exercisename)

and I am displaying each form in the formset in my template so the user can individually edit the instance:

<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>

Stuck as to why this isn't working. The form displays as it should and this method has previously worked for adding objects, but I am still unable to use it to replace one of those objects in the queryset. Am I missing something I should be doing differently?

Edit:

Turns out the solution was to change my request.method statement to:

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

Which allows me to save each form in the formset individually, seeing as I am altering only a section of the formset.

Your code is working for me. Maybe you have changed your environment setup or something else. When you submit your form, Is there any error showing to you? If so show us your error details.

You can try like this:

def edit_sets(request, exercisegroup_id):
    exercisename = ExerciseName.objects.get(pk=exercisegroup_id)
    SetLoggerFormSet = inlineformset_factory(ExerciseName, SetLogger, fields=('weight','reps',))

    formset = SetLoggerFormSet(instance=exercisename)


    if request.method == 'POST':  
      formset = SetLoggerFormSet(request.POST, instance=exercisename)
      if formset.is_valid():
         formset.save()
      else:
        print("something is wrong in validation")
        print(formset.errors)
        formset = SetLoggerFormSet(instance=exercisename)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM