title: How to edit an object using model form in django?
body: <p>This may possibly be a duplicate of <a href="https://stackoverflow.com/a/24784867/11968044">this</a> answer. Currently, i'm working on updating an object using the same model form that is used to create the object.</p>
  
  <p>my <code>views.py</code> looks like: (as from the answer):</p>
  
  <pre class="lang-py prettyprint-override"><code>def newpost(request):
      form = PostForm(request.POST)
      if request.method == "POST":
          if form.is_valid():
              obj = form.save(commit=False)
              obj.save()
              return redirect('newpost')
      return render(request, 'console/newpost.html', {'form':form})
  
  def editpost(request, pk):
      obj = Post.objects.get(id=pk)
      form = PostForm(instance=obj)
      if request.method == "POST":
          if form.is_valid():
              obj = form.save(commit=False)
              obj.save()
              return redirect('editpost')
      return render(request, 'console/editpost.html', {'form':form})
  </code></pre>
  
  <p>And my html form in <code>editpost</code> looks like:</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;form method="POST" action="{% url 'newpost' %}"&gt;
      {% csrf_token %}
      {{form.as_p}}
      &lt;button type="submit"&gt; Submit&lt;/button&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>and my <code>urls.py</code> looks like:</p>
  
  <pre class="lang-py prettyprint-override"><code>path('console/post/', c_views.newpost, name='newpost'),
  path('console/post/&lt;int:pk&gt;/', c_views.editpost, name='editpost'),
  </code></pre>
  
  <p>And the above codes works perfectly fine, but creates a new instance, with the data of the object taken from pk.</p>
  
  <p>I added a <code>obj.delete()</code> code like this:</p>
  
  <pre class="lang-py prettyprint-override"><code>def editpost(request, pk):
      obj = Post.objects.get(id=pk)
      form = PostForm(instance=obj)
      obj.delete()
      if request.method == "POST":
          if form.is_valid():
              obj = form.save(commit=False)
              obj.save()
              return redirect('editpost')
      return render(request, 'console/editpost.html', {'form':form})
  </code></pre>
  
  <p>This code gives me the exact thing i wanted, but i know it's not a good practice. My question here is, is this a correct way or am i lagging somewhere.
  I know the action in my <code>editpost</code> html should not be <code>{% url 'newpost' %}</code>, but if i use <code>{% url 'editpost' %}</code> i don't know how to pass the pk value inside the url tag. Can anyone suggest me the correct way? </p>