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!
Solution was to override the save method in the ModelForm: