Question

I've created a basic Django app that contains books/authors/publishers as per the Django Book - trying to use a ModelForm to create a means to modify existing books - the problem is that the 'authors' field is a ManyToManyField and when I choose a choice on the ModelForm it simply wipes the existing selection and doesn't save the new one?

models.py

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField2(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

    def __unicode__(self):
        return self.title

class BookForm(ModelForm):
    class Meta:
        model = Book

    authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all(), required=False)

views.py

def editBook(request, b=None):
    instance = None
    if b is not None:
        instance = Book.objects.get(title=b)
    if request.method == 'POST':
        form = BookForm(request.POST, instance=instance)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = BookForm(instance=instance)
    return render_to_response('book_form.html', {'form':form})

Cheers!

edit I have just found several articles that encourage the following in views.py

authors = form.save(commit=False)
authors.user = request.user
authors.save()
form.save_m2m()

But still not having any luck - can't be this hard!

Was it helpful?

Solution

Solution was to override the save method in the ModelForm:

def save(self, commit=True):
    authors =[]
    for a in self.cleaned_data['authors']:
         authors.append(Author.objects.get(first_name=t.first_name))

    b = super(BookForm, self).save(commit=commit)

    for a in authors:
        b.authors.add(a)
    b.save()

OTHER TIPS

Because you override authors field. Either don't do it and let Django do it's job, or handle it manually.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top