1

I opened up a prior issue on SO regarding manytomany fields not being saved in Django Createview here. Django CreateView With ManyToManyField After troubleshooting most of today, I have found that this code actually works:

class CreateAuthorView(LoginRequiredMixin,CreateView):

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.save() 
        instance = form.save()

        if instance.access_level == "Custom":
            obj = NewAuthor.objects.get(secret=instance.name)
            obj.access.add(instance.created_by.id)
            print(instance.created_by.id)
            print(obj.access.all())
            instance = form.save()
            obj.save()
            form.save_m2m()
            instance = form.save()

        return super(CreateAuthorView, self).form_valid(form)

When I issue the print(obj.access.all()) I can see in my console that the

    obj.access.add(instance.created_by.id)

Line of code actually does exactly what I want it to do...it adds the created_by.id to the access(ManyToManyField) field that I have defined in my model. However, when the record actually gets cut, only the values that the user selected in the form are added to the access field, and the created_by.id never makes it to the database.

Should I be overriding CreateView somewhere else in order for the created_by to take affect? It appears as if my initial update in form_valid is being overwritten is what I suspect. Actually I've proven it because my update is in fact in my console but not making it to the database. Thanks in advance for any thoughts on how best to solve.

Steve Smith
  • 1,019
  • 3
  • 16
  • 38

1 Answers1

0

I found the answer to my question via this SO question. It turns out you have to override SAVE in the ModelForm in order to save M2M fields. Save Many-To-Many Field Django Forms This one was tricky.

Steve Smith
  • 1,019
  • 3
  • 16
  • 38