FLOG build - article list

In this chapter, we study Django's MTV


MTV is the initial letter of Models, Templates and Views

Next, let's study the model

Models - Models

What is a model?

A model is a single, definitive source of information about your data. It contains the basic fields and behavior of the data you store. Typically, each model maps to a single database table.

——From Jian Shu

Next, we write the model of the article

Open article/models.py, empty and enter:

from django.contrib.auth.models import User
from django.utils import timezone
from django.db import models

class ArticleModel(models.Model):
	author = models.ForeignKey(User, on_delete=models.CASCADE)  # author
	title = models.CharField(max_length=100)  # title
	content = models.TextField()  # text
	create = models.DateTimeField(default=timezone.now)  # Creation time (used for sorting)
	update = models.DateTimeField(auto_now=True)  # Update time

	class Meta:
		ordering = ('-create',)

	def __str__(self):
		return self.title
  • ForeignKey: form a one to many relationship between User and author
  • on_delete=models.CASCADE: when the User deletes, the articles created by him are deleted together
  • CharField: the field used to store the string
  • max_length=100: the maximum length of the title is 100 words
  • TextField: a field used to store a large number of characters
  • DateTimeField: a field used to store time
  • ordering = ('-create',): sort by creation time, that is, old posts will be at the bottom of the data table
  • __ str__: It can be simply understood as displayed information

So the model is finished

Templates  - Template

God horse is a template?

The template in Django is equivalent to V in the traditional MVC mode, while in Django's MVT, the template is T. Django template is very useful in the traditional development form of non separation of front and rear ends, but Django template is basically useless in today's environment of separation of front and rear ends.

The template can obtain data from the HttpResponse returned by the view, and then process the data for display.

——From CSDN

Template path configuration

Open settings.py and modify the following lines:



        'DIRS': [os.path.join(BASE_DIR, 'templates')],  # Modify here



It's very easy to understand. It means that the directory of the template is in the templates folder

Write template

Create a new templates folder in the root directory, then an article folder in it, and then an index.html in the article folder to represent the article list

Now the directory structure is:

│  manage.py
│          ...
│          ...

Write index.html, which is scrawled first

<!-- Django In the template for grammar -->
{% for article in articles %}
    {{ article.title }} <!-- Get the title of the article -->

<!-- End cycle -->
{% endfor %}

Views - View

Open article/views.py and enter:

from django.shortcuts import render

from .models import ArticleModel

def index(request):
	articles = ArticleModel.objects.all()

	context = { 'articles': articles }
	return render(request, 'article/index.html', context)
  • def index(request): View function of article list
  • articles = ArticleModel.objects.all(): get all articles in the model
  • return render(request, 'article/index.html', context): pass the context into the template index.html. Index.html uses the for loop to get out each article

Configure urls


from django.urls import path

from . import views

app_name = 'article'

urlpatterns = [
	path('index/', views.index, name='index'),  # Bind index / to the view function in views

Migrate database

After updating models.py every time, don't forget to migrate the database

Open CMD and enter the following code

python manage.py makemigrations

python manage.py migrate

Configure admin

After configuring admin, you can modify the data in the model in the background


from django.contrib import admin

from .models import ArticleModel

# Modify page title
admin.site.site_title = 'FLOG back-stage management'
admin.site.site_header = 'FLOG back-stage management'

# Register ArticleModel

Next, we register an administrator account, open CMD and enter:

python manage.py createsuperuser

Then, according to the prompt, enter the account email password, and the creation is basically successful without error

(it is normal not to display your password when entering it, because Django will never disclose your password)

Exciting moment

Next, we're going to run the project. Are you excited

Open CMD and enter:

python manage.py runserver

Then he will show:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
November 09, 2021 - 19:44:59
Django version 2.2, using settings 'FLOG.settings'
Starting development server at
Quit the server with CTRL-BREAK.

Find the URL at the end of the penultimate line, which is the URL where Django runs

Visit in the browser, which is the background url

If you see the following page, it indicates success

Enter the user name and password just now and log in

Click on the Article models above, remember? This is the model we knocked last time

Click add ARTICLE MODEl, fill in the title of the article and other information, and then save to create an article

Write more articles like this, and then visit /. This is the article list page


You can see that the title of the article just written has appeared on the page, but the UI is worrying. We will beautify it in the next chapter

At the end of this article, if you have any questions, you can comment in this chapter or send an email to 2912654354@qq.com  

Tags: Python Django

Posted on Tue, 09 Nov 2021 21:20:14 -0500 by 99degrees