Rewrite view function

In the previous chapter we took a look at the workflow of views.

** To make the view really useful, ** rewrite the article_list function in article/views.py:

article/views.py

from django.shortcuts import render

# import data model ArticlePost
from .models import ArticlePost

def article_list(request):
    # Retrieve all blog posts
    articles = ArticlePost.objects.all()
    The object you want to pass to templates
    context = { 'articles': articles }
    The # render function loads the template and returns the context object
    return render(request, 'article/list.html', context)
Copy the code

The code is also straightforward, and the analysis is as follows:

  • .modelsRepresents from the current foldermodels.pyIn-file importArticlePostData classes
  • ArticlePost.objects.all()fromArticlePostThe data class takes all the objects (that is, blog posts) and passes them toarticlesvariable
  • contextDefines the objects that need to be passed to the template, i.earticles
  • And then it comes backrenderFunction:
    • The first variable is fixedrequestObject, just write it like that
    • The second variable defines the location and name of the template file, i.earticle/list.html
    • The third variable defines the object that needs to be passed in the template file, i.econtext

So there you have your view function.

Write a template

In the previous view we defined the template location to be in article/list. HTML, so go to the “templates” folder at the root, then the “article” folder, then the “list. HTML” file:

My_blog │... ├ ─ article │... └ ─ my_blog │... └─templates ├ ─ list.htmlCopy the code

You may have noticed that Django files used to end with.py, which stands for Python files; So the template file suffix here is.html, what is that?

**HTML is a markup language used to create web pages. ** It is used for structuring information, marking which text is heading, which text is body, etc. (not only that, of course). It can also be simply referred to as a document that “formats data” in the same way that you use Office Word to write documents.

In the list.html file, write:

templates/article/list.html

{% for article in articles %}
	<p>{{ article.title }}</p>
{% endfor %}
Copy the code

As a Web framework, Django uses templates to dynamically generate HTML that contains special syntax for describing dynamic content:

  • {% for article in articles %} : articles is a collection of articles passed to the context of the view function. {% for %} takes the elements in articles, names them article, and performs the following operations. At the end, {% endfor %} tells Django where the loop ends.

  • Use the. Symbol to access the properties of a variable. Article here is an article in the model; In the previous ArticlePost, we defined the title of the article as title, so you can use article.title to access the title of the article.

  • is HTML, wrapped in a paragraph of text.

This was defined in the previous chapterurls.py, so no changes are needed.

Everything’s fine. Take a deep breath. Save all the files, input address http://127.0.0.1:8000/article/article-list/ in the browser, get the following error:

It seems that success never goes smoothly.

Error analysis

Fortunately, Djangos provides an excellent error-handling system for finding bugs quickly.

The first line says, TemplateDoesNotExist, that Django didn’t find the list.html file. Double check the directory, file name is correct, no problem continue to read.

And then there are these two lines:

...django\contrib\admin\templates\article\list.html (Source does not exist)
...django\contrib\auth\templates\article\list.html (Source does not exist)
Copy the code

It appears that Django searched in both locations, didn’t find the required files, and returned an error saying “template file not found.”

Now that I’ve located the problem, where do I “tell” Django where my templates are?

The answer lies insettings.pyIt holds the various initial configurations of a Django project.

Go to this and add os.path.join(BASE_DIR, ‘templates’) :

my_blog/settings.py

TEMPLATES = [
    {
        ...
        # define template location
        'DIRS': [os.path.join(BASE_DIR, 'templates')],... },]Copy the code

This means that the templates file is in the templates folder at the root of your project, so look for it.

Good, save the file, restart the server, and refresh the browser as follows:



Success!

Although simple, but has completely gone through the MTV (Model, Template, view) the entire loop.

Don’t get excited. The best is yet to come.

conclusion

In this chapter, we rewrote the view and wrote a simple template that was successfully associated with the previous model.

The next chapter will learn how to write a beautiful web page template.

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