0

I am trying to use a Django CreateView and ultimately update a ManyToMany Field if the user selects a certain value. I can get the form to validate, but ultimately it isn't updating the manytomanyfield in the database. Not sure what I'm doing wrong. I have referenced this similar SO issue, Django ManyToMany CreateView Fields In Both Tables but it was of no help to me. I recently found this link...Django CreateView: How to perform action upon save and it seems very close to the issue I'm having. Thanks in advance for any thoughts.

My code:

class AuthorView(LoginRequiredMixin,CreateView):
    model = NewAuthor
    form_class = NewAuthorForm
    template_name = 'create_author.html'

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

        if instance.status == 'Submitted':

            if instance.choice == "Custom":
                instance.access.add(instance.created_by)  
                form.save_m2m()

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

Here is my model:

class NewAuthor(models.Model):

CHOICES = (
    ('',''),
    ("Default",Default ),
    ("Custom",Custom ),
)

STATUS_CHOICES = (
    ("Submitted","Submitted"),
    ("Pending","Pending")
)

status = models.CharField(choices=STATUS_CHOICES,default="Submitted",max_length=20)
choice = models.CharField(choices=CHOICES,blank=True,max_length=300)
created_by = models.ForeignKey(User,null=True,on_delete=models.DO_NOTHING,related_name='created_by_user')    
access = models.ManyToManyField(User,related_name="new_author_individual_access")

This passes form validation, but doesn't save the created_by value in the manytomany field. I have tried to incorporate form.save(commit=False) and a subsequent form.save(), but that doesn't seem to help either. I am ultimately trying to add the created_by user to the manytomany field conditionally, but no luck so far.

As a quick update, if I add the form.save_m2m() to my code, it actually does add the created_by to the database...but I also get an error that says object has no attribute 'save_m2m'. It actually adds the created_by but then quits because of this error. Now if I add commit=False, no errors but the database doesn't get updated either.

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

2 Answers2

0

I think you forgot to set the value of created_by, you are saving it with a null value since it's the default in your models. Try

    instance = form.save(commit=False)
    instance.created_by = request.user # or whatever value
    instance.save()
Johann
  • 923
  • 2
  • 8
  • 16
0

This post was the answer to my problem. Save Many-To-Many Field Django Forms ModelForms are great....but not with m2m apparently...That was exhausting...

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