After the article list page, of course, also need details page, convenient for users to a certain article interested in in-depth reading.

Writing view functions

Open article/views.py and add the view function article_detail() to the article details page:

article/views.py

...

# Article details
def article_detail(request, id):
    # fetch the corresponding article
    article = ArticlePost.objects.get(id=id)
    The object to pass to the template
    context = { 'article': article }
    Load the template and return the context object
    return render(request, 'article/detail.html', context)
Copy the code
  • article_detail(request, id)I have a lot of delta functionsidThis parameter. Note that when we write model, we dont write a field called ID. This is the Primary Key (PK) Django automatically generates for indexing tables. It’s the only way to know which article to pull out.
  • ArticlePost.objects.get(id=id)Fetch the only article whose ID matches all articles.

Then write article/urls.py and configure the routing address:

article/urls.py

...

urlpatterns = [
	...
	
    # Article details
    path('article-detail/<int:id>/', views.article_detail, name='article_detail'),]Copy the code


: the new syntax for path in Django2.0 uses ** Angle brackets <>** to define the parameters to be passed. Here we need to pass an integer named ID to the view function.

To reiterate, older versions of Django do not existpathThe grammar.

Write a template

Create a new detail.html file in templates/article/ and write the following code:

templates/article/detail.html

<! -- extends indicates that the page extends from the base.html file -->
{% extends "base.html" %}
{% load staticfiles %}

<! Add the title defined in base.html -->{% endblock title %}<! -- Write the content defined in base.html -->
{% block content %}

<! -->
<div class="container">
    <div class="row">
        <! -- Title and author -->
        <h1 class="col-12 mt-4 mb-4">{{ article.title }}</h1>
        <div class="col-12 alert alert-success">{{article. Author}}</div>
        <! -- Text -->
        <div class="col-12">
            <p>{{ article.body }}</p>
        </div>
    </div>
</div>

{% endblock content %}
Copy the code

Here we use{{ article.xxx }}Extract the title, author, and body of the article.

We’ve already created a few articles in the background, and here we’ll pull out an article with ID 1 to test the effect.

After running development server, type http://127.0.0.1:8000/article/article-detail/1/: in your browser

Optimizing web entry

Although the article details feature is implemented, the way to access it by entering a URL is too unfriendly.

Rewrite header. HTML so that users can return to the home page via the article link on the right side of the navigation bar:

templates/header.html

...
<div>
    <ul class="navbar-nav">
        <li class="nav-item">
        
            <! Href --> 
            <a class="nav-link" href="{% url 'article:article_list' %}">The article</a>
          
        </li>
    </ul>
</div>.Copy the code

Notice how the href is rewritten here:

  • Href defines the address to which the link jumps
  • {% url '...' %}Django-specified syntax for specifying an address
  • About it'article:article_list'Explanation:
    • In front ofarticleIt is in the project root directoryurls.pyThe name of the app defined in
    • At the back of thearticle_listIt’s in the appurls.pyA specific routing address defined in

This way, the link redirect is configured so that Django can resolve the url to the correct address, no matter how the url itself changes, as long as the name of the url stays the same.

Of course, you can also write the url address directly in the href, but if the URL changes, all related links will be invalid, reducing maintainability.

Then rewrite list.html so that the user can click the Read article button to access the details of the article:

templates/article/list.html

...

<div class="card-footer">

    <! Href -->
    <a href="{% url 'article:article_detail' article.id %}" class="btn btn-primary">Read this article</a>
    
</div>.Copy the code

Notice how the id of the article is passed:

  • inlist.htmlthroughhref="{% url 'article:article_detail' article.id %}"Pass the ID toarticle/urls.py
  • inarticle/urls.pythrough<int:id>Pass it to the view functionarticle_detail()
  • In the view functionarticle_detail(), through the parameteridObtain the id value of the article, and processing, and finally locate the article object to be obtained

Now we can access different pages on the site through links, without having to manually enter urls. Of course, this is the basis of modern websites.

conclusion

We now also have the ability to view article details and optimize the experience of switching between pages.

In the next chapter, you’ll learn how to use Markdown syntax to type your text.

  • 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.