如果要从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
edit添加和编辑使用相同的视图,但是只有编辑URL模式将ID传递给视图。为了使它与您的表单一起使用,您需要author从表单中省略该字段:
class ArticleForm(forms.ModelForm):
class meta:
model = Article
exclude = (‘author’,)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)