Home > Software design >  How do you modify manytomanyfield in form in django?
How do you modify manytomanyfield in form in django?

Time:12-09

I was wondering how you can change the value of a many-to-many field in a django form. Preferably, I would like to change the value within the def form_valid of my Modelview. Here is a part of the form_valid in my view that I am having trouble with:

lesson = Lesson.objects.all().first()

for i in lesson.weekday.all():
    form.instance.weekday.add(i)
    form.instance.save()

Here, weekday is a many-to-many field. However, the form saves the "submitted" values of the weekday by the user, and not the changed one as shown in the above code. Interestingly, the below code works, although it is not a many-to-many field:

form.instance.name = lesson.name
form.instance.save()

Thank you, and please leave any questions you have.

CodePudding user response:

I suspect that you are running the code before calling the super method. The code in the super method can look like this:

def form_valid(self, form):
    self.object = form.save()
    return super(ModelFormMixin, self).form_valid(form)

When form.save() runs clear all ManyToMany related values and sets the form values.

Probably you need run your code after calling the super method:

def form_valid(self, form):
    # some code here...
    return_value = super(MyView, self).form_valid(form)
    lesson = Lesson.objects.all().first()
    for i in lesson.weekday.all():
        self.object.weekday.add(i)
        # self.object.save() # Dont need call save here

    return return_value

  • Related