我已经根据Django Book创建了一个基本的Django应用程序,其中包含书籍/作者/发布者 - 试图使用ModelForm来创建修改现有书籍的方法 - 问题是“作者”字段是ManyToManyField当我在ModelForm上选择一个选项时,它只是擦除现有的选择而不保存新的选择?
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})
干杯!
修改 我刚刚在views.py
中发现了几篇鼓励以下内容的文章authors = form.save(commit=False)
authors.user = request.user
authors.save()
form.save_m2m()
但仍然没有运气 - 不能这么难!
答案 0 :(得分:2)
解决方法是覆盖ModelForm中的save方法:
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()
答案 1 :(得分:0)
因为您覆盖了authors
字段。要么不这样做,让Django做它的工作,要么手动处理它。