Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you are extending your form from a ModelForm, use the <code>instance</code> keyword argument. Here we pass either an existing <code>instance</code> or a new one, depending on whether we're editing or adding an existing article. In both cases the <code>author</code> field is set on the instance, so <code>commit=False</code> is not required. Note also that I'm assuming only the author may edit their own articles, hence the HttpResponseForbidden response.</p> <pre><code>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 }) </code></pre> <p>And in your <code>urls.py</code>:</p> <pre><code>(r'^article/new/$', views.edit, {}, 'article_new'), (r'^article/edit/(?P&lt;id&gt;\d+)/$', views.edit, {}, 'article_edit'), </code></pre> <p>The same <code>edit</code> view is used for both adds and edits, but only the edit url pattern passes an id to the view. To make this work well with your form you'll need to omit the <code>author</code> field from the form:</p> <pre><code>class ArticleForm(forms.ModelForm): class Meta: model = Article exclude = ('author',) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload