This is the sixth day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

The first article in this series: Quickly create a Django project, and the Python environment will have you covered

Create an admin account

First, we start the debugging project in vscode, then open the terminal, enter the corresponding project directory, execute the command pipenv shell to enter the virtual environment, and then execute the following command to create an admin account.

python manage.py createsuperuser
Copy the code

Once created, we can use our browser to access the url below (make sure the project is already started in vscode).

http://127.0.0.1:8000/admin
Copy the code

The admin login page is automatically displayed.To log into djangos admin background, enter the account and password you just created.There are two by defaultGroups(Default is null),Users(There are admin accounts created by ourselves, we can also create other administrator accounts directly here).

Settings. py basic introduction

Open settings.py in vscode (you can also use pycharm or any other code development tool) and you can see the source code. You can use some English annotations to get a sense of what the code means. Here I have selected some common Settings that need to be modified to explain them to you. So introduce it (or you can skip it, of course).

# You can also go to the official website to see the related introduction (recommended)For more information on this file, See https://docs.djangoproject.com/en/3.2/topics/settings/ For a full list of Settings and their values. See https://docs.djangoproject.com/en/3.2/ref/settings/Copy the code
# True indicates that debugging information will be output at the terminal. In a production environment, set this value to False
DEBUG = True

You can set the IP address to allow access. The default is 127.0.0.1
ALLOWED_HOSTS = []

Every new app should be installed here
INSTALLED_APPS = [
    'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles',]The default is DjangoTemplates, which can also be changed to Jinja2
Here we need to set DIRS and add a templates file in the root directory
# APP_DIRS set to True, False will not work with Django admin
All templates are managed in the templates file in the root directory
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates'.'DIRS': [os.path.join(BASE_DIR, 'templates')].'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug'.'django.template.context_processors.request'.'django.contrib.auth.context_processors.auth'.'django.contrib.messages.context_processors.messages',],},},]Sqlite3 is used by default for database configuration
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3'.'NAME': BASE_DIR / 'db.sqlite3',}}# Project language
LANGUAGE_CODE = 'en-us'
# Time zone
TIME_ZONE = 'UTC'

Static resource file path
STATIC_URL = '/static/'
Copy the code

Through the above notes, we can first modify the project language and time zone to Chinese, and change the time zone to our ~

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'
Copy the code

After modification and saving, the project is started in debugging mode, so after saving, the system will automatically update. We do not need to start the project again, we directly refresh the previously visited management background page, and we will find that the page content becomes Chinese.

Create a blog app

First, we start the debugging project in vscode, then open the terminal, enter the corresponding project directory, execute the command pipenv shell to enter the virtual environment, and then execute the following command to create an admin account.

python manage.py startapp blog
Copy the code

When we run it, we look at the directory structure, and we see that we have a blog directory, which is the app that we just created,It is important to note that myBlog is the directory where we created the project, which can be understood as an entry point to the program, containing configuration files, system routing, and Web services gateway interface configuration.

About the files in the newly created App Blog directory (a brief introduction) :

  • Migrations migrations file, which stores database operation statements that are migrated from models to the database.
  • Admin.py registers the model file, and the registered model can be displayed in the admin management background.
  • Apps.py allows you to set additional application configurations and apply them.
  • Models. py data model file, database design mainly here, directly create class objects;
  • Tests. py test file, mainly used for app testing;
  • Py view file, mainly write function realization function;
  • Urls.py (need to create your own) routing file, note the declaration of routing relationships.

Register the newly created app in Settings

To create an app, you need to add the newly created app to INSTALLED_APPS in your Settings.

INSTALLED_APPS = [
    'django.contrib.admin'.'blog'.# blog app
]
Copy the code

To create the Article Models

In blog/models.py, we create an Article model, including the author of the Article, the title of the Article, the summary of the Article, and the body of the Article. Other attributes should be added: title graph, Article tag, page views, etc.

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

# Create your models here.
class Article(models.Model) :
    Create a basic article object including: author, title, summary, later in the body need to add: title image, article tag, views, etc.
    # Article author, author is associated with the system's native User model via the models.foreignKey
    The on_delete parameter is used to specify how to delete data from two associated tables.
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    # Article title
    title = models.CharField(max_length=255, null=False, blank=False)
    # Article summary
    summary = models.CharField(max_length=255, null=False, blank=False)
    # Body of the article
    content = models.TextField()
    
    The inner class class Meta is used to define metadata for the model
    class Meta:
        Ordering specifies the orderin which the model returns data
        # '-title' indicates that the data list is displayed in descending order by title name
        ordering = ('-title'.)# db_table specifies the name of the table after mapping to the database
        db_table = 'tb_article'
        # Djangos daemon displays the name
        verbose_name = 'Article Management'
        verbose_name_plural = verbose_name

    The function __str__ defines the content of the return value when the STR () method of an object is called
    It is most commonly used as a display value for objects in the Django admin background. Therefore, you should always return a friendly and readable string for __str__
    def __str__(self) :
        # Return the article title, and Djangos admin displays the item name
        return str(self.author) + The '-' + self.title
Copy the code

Once the module is created, we need to register the Article model with blog/admin.py so that it will be displayed in the admin system,

from django.contrib import admin
from blog.models import Article

# Register your models here.
# register model
admin.site.register(Article)
Copy the code

In addition, we need to perform the migration command on the terminal, so that the system will automatically create the corresponding table in the database according to the properties in the Article model.

Run the following command to enter the virtual environment
python manage.py makemigrations
python manage.py migrate
Copy the code

After setting up and registering the model, and migrating the mapping to the database, we can start the application and access it directly from the browserhttp://127.0.0.1:8000/admin, if you need to log in, you can directly log in with the admin account created before, after logging in, we can see our new article management module.Click into the article management module, we can add, delete and check the operation of the article, the default is empty, I have added a new article below.We can clickAdd article management, we can create a new article, we select the author (and the user in the system is linked, so we can only choose directly), input the title of the article, article summary, article content, after the day click save, you can also click save and add another or save and continue to edit.After saving, it will automatically jump to the article management page to display all the articles in the current database in a list.Click a random article, you can enter the corresponding article editing interface, you can modify or delete the content.

See you next time. I’m a cat lover and a tech lover. If you find this article helpful, please like, comment and follow me!