如果您要从 ModelForm 扩展表单,请使用instance
关键字参数。这里我们传递一个现有的instance
或新文章,具体取决于我们是编辑还是添加现有文章。在这两种情况下author
字段是在实例上设置的,所以commit=False
不需要。另请注意,我假设只有作者可以编辑自己的文章,因此会出现 HttpResponseForbidden 响应。
from django.http import HttpResponseForbidden
from django.shortcuts import get_object_or_404, redirect, render, reverse
@login_required
def edit(request, id=None, template_name='article_edit_template.html'):
if id:
article = get_object_or_404(Article, pk=id)
if article.author != request.user:
return HttpResponseForbidden()
else:
article = Article(author=request.user)
form = ArticleForm(request.POST or None, instance=article)
if request.POST and form.is_valid():
form.save()
# Save was successful, so redirect to another page
redirect_url = reverse(article_save_success)
return redirect(redirect_url)
return render(request, template_name, {
'form': form
})
而在你的urls.py
:
(r'^article/new/$', views.edit, {}, 'article_new'),
(r'^article/edit/(?P<id>\d+)/$', views.edit, {}, 'article_edit'),
相同edit
view 可用于添加和编辑,但只有编辑 url 模式才会将 id 传递给视图。为了使其与您的表单配合良好,您需要省略author
表单中的字段:
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
exclude = ('author',)