[Django]-Django ManyToMany from String in CreateView

4👍

Here you are settings “tags” attribute to None, but your publication does not have a Primary Key yet, so the many to many relationship is having a hard time.

What you have to do is to save it first.

You will find more about this here

def form_valid(self, form):
    pub = form.save(commit=False)
    pub.save()
    pub.tags=None


    tags=str(self.request.POST.get('tags'))
    tags = tags.split(',')
    tl=[]
    for tag in tags:
        tl.append(Tag.objects.get_or_create(name=tag))
    pub.tags.add(tl)
    pub.save()
    form.save_m2m()
    return HttpResponseRedirect(self.get_success_url())
👤Nezo

Leave a comment