我创建了一个基本的Django应用程序,其中包含书籍/作者/出版商按照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()
但仍然没有任何运气-不可能这么难!
解决方案是重写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()
因为您覆盖了authors
字段。要么不做,让Django来做,要么手动处理。