So far we have finished creating, deleting, and viewing articles, and the last thing left is to modify the finished articles.

In fact, modifying an article is similar to creating a new article, with two differences:

  • The modification is based on the original article, so you need to pass the ID to indicate the specific article to be modified
  • The old content needs to be filled into the form as the default value when the page loads, so the article object needs to be passed tohtmlIn the

With that in mind, let’s write the view function first.

The view function

Add the view function article_update() to ariticle/



# Update the post
def article_update(request, id):
    The view function that updates the article submits the form via the POST method, and the titile, body, and GET methods that update the initial form page ID: the article ID

    Get the specific article object that needs to be modified
    article = ArticlePost.objects.get(id=id)
    Determine whether the user submits form data for POST
    if request.method == "POST":
        Assign the submitted data to the form instance
        article_post_form = ArticlePostForm(data=request.POST)
        Determine whether the submitted data meets the requirements of the model
        if article_post_form.is_valid():
            Save the new title and body data and save it
            article.title = request.POST['title']
            article.body = request.POST['body']
            Return to the modified article when you are done. The id value for the article to pass in
            return redirect("article:article_detail", id=id)
        If the data is invalid, return an error message
            return HttpResponse("There is something wrong with the form. Please fill it out again.")

    GET data if user GET requests it
        Create a form class instance
        article_post_form = ArticlePostForm()
        # Assign context, passing the article object in to extract the old content
        context = { 'article': article, 'article_post_form': article_post_form }
        Return the response to the template
        return render(request, 'article/update.html', context)
Copy the code

The updated view is very similar to creating an article, but with a slight difference:

  • The id of the article is passed in as an argument
  • When a user posts a form, he does not create a new article, but modifies it in the previous article
  • redirectInstead of returning the list of articles, the function returns to the modified article page, so you need to pass in the id of the article as well, as specified by the URL
  • GET gets the page and passes the article object to the template for subsequent calls

Write a template

The template file is more like the one used to create the article, but let’s rewrite it here.

New templates/article/update the HTML and write:

Templates/article/update. HTML {% extends "base. HTML" %} {% load staticfiles %} {% block title %} update articles {% endblock title %} {% block content %}<div class="container">
    <div class="row">
        <div class="col-12">
            <form method="post" action=".">
                {% csrf_token %}
                <div class="form-group">
                    <label for="title">The article title</label>
                    <! Set the initial value of the text box to the old content in the article object title field -->
                    <input type="text" class="form-control" id="title" name="title" value="{{ article.title }}">
                <div class="form-group">
                    <label for="body">The article body</label>
                    <! The value attribute is not required for the text field, so you can embed the data in the tag body directly.
                    <textarea type="text" class="form-control" id="body" name="body" rows="12">{{ article.body }}</textarea>
                <button type="submit" class="btn btn-primary">complete</button>
{% endblock content %}
Copy the code

In the template, the old title and body of the article are passed in as initial values, and the rest is the same as in the template for the new article.

Since these two functions and templates are very similar, can ** be merged into one function and template? ** Of course it is possible, combining functions of the same function can make the code more concise and beautiful, but also easy to maintain later. Interested readers can try it out for themselves.

The URL and entrance

The following routine is familiar: configure the route article/



urlpatterns = [
    # Update the post
    path('article-update/<int:id>/', views.article_update, name='article_update'),]Copy the code

Tempaltes/article/detail. The article details page HTML to add modify articles of entry:


<div class="col-12 alert alert-success">Author: {{article. Author}} ·<a href="#" onclick="confirm_delete()">Delete articles</a>
    · <a href="{% url "article:article_update"} ">Edit the articles</a>
Copy the code

Start the server and you can see the ability to modify the article. Similarly, if something goes wrong, don’t worry. Look for clues on the Debug page and ask the network for help.


So far we have achieved an article of the increase, delete, change, check four basic functions, is also a small achievement.

Of course there are many more advanced functions that can be done, but let’s take a break and celebrate with a bottle of happy water.

The next chapter begins with the more pressing issue of user management.

  • If you have any questions please leave a message on Doucet’s personal website and I will reply as soon as possible.
  • Or Email me a private message: [email protected]
  • Project code: Django_blog_tutorial

Please inform the author and indicate the source for reprinting.