save_m2m方法只用来存储多对多的关系:
当你同时满足下面两个条件时,你必须要使用此方法——
1、使用了save(commit=False)方法,添加了额外的字段
2、model里有多对多的关系(比如tags)
假设我们文章模型里有tags这个多对多的字段,我们还需要在视图里增加一行save_m2m, 否则多对多关系不会被存储。
def article_create(request):
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
article = form.save(commit=False)
# commit=False tells Django that "Don't send this to database yet.
article.author = request.user # Set the user object here
article.save() # Now you can send it to DB
form.save_m2m()
return HttpResponseRedirect("/blog/")
else:
form = ArticleForm()
return render(request, 'blog/article_create_form.html', {'form': form})