"Django learning diary" starts from scratch and builds a student management system

In my opinion, starting with a simple project, you will learn quickly.

In a project, when you find a problem, you say it.

If you have any mistakes, please correct them. I will correct them. Also welcome to exchange.

There are many basic python tutorials on the Internet. After all, they are basic, so most of them are free. You can have a look at them. You can understand a little. Along with doing simple projects, learning

First, open pycharm to create a project named: stu_test, as shown in the figure:


Select Django on the left, where my project path is: E:\django_test\stu_test (stu_test is my project name)

Choose the python interpreter. Here, I use the virtual environment of my computer to choose the second option. The first option is to create a virtual environment.

At the bottom, fill in the name of APP, and use app01 here (it's just for the learning stage, the name can be picked up casually, the amount of my words is too small, everyone has an idea)

Click Create to Create our project. (wait for the loading to complete), the project is created successfully, and the directory structure is as follows:

After creation, set it first (stu_test/stu_test/settings.py)

Because it was created by pycharm, the app was automatically added for us, and the model was configured, so we can ignore it first

Let's use sqlite first. It's brought by Django. We're just learning now, and it's enough for the time being.

First, pull it to the bottom and modify the following two items, one is the language environment and the other is the time zone.

LANGUAGE_CODE = 'zh_hans'
TIME_ZONE = 'Asia/Shanghai'

Next, we need to add fields. Let's do a simple analysis and build a structure, as shown in the figure: (it's written in Notepad, a little bit sloppy. You can recommend some useful tools.)

It can be found from the above figure that the fields include class, name, gender and age.

Each class has its name, gender and age. (the words are not clear. The best expression is code. Let's go to code):

Location: stu_test/app1/models.py

from django.db import models
# All added tables need to inherit from models.Model
# Create a class table named StuClass
class StuClass(models.Model):
		#models.CharField() field type is char
    # Verbose [name = "class" set the field name to class
    # Max'length = 10 is 10
    # null=False cannot be empty
    # unique=True duplicate not allowed
    class_stu = models.CharField(verbose_name="class", max_length=10, null=False, unique=True)
		# Auto now add = time to add true
    # Add the following two fields for convenient statistics maintenance
    add_time = models.DateTimeField(verbose_name="Adding time", auto_now_add=True)
		# Auto? Now = true current time
    updata_time = models.DateTimeField(verbose_name="Adding time", auto_now=True)


# Create a student table named Students
class Students(models.Model):
    name = models.CharField(verbose_name="Full name", max_length=6, null=False)
    age = models.IntegerField(verbose_name="Age", null=False)
		# Construct a tuple
    genders = (
        (0,"male"),
        (1,"female"),
    )
    # choices means choosing. choices=genders choose from genders
    gender = models.IntegerField(verbose_name="Gender", choices=genders)
    add_time = models.DateTimeField(verbose_name="Adding time", auto_now_add=True)
    updata_time = models.DateTimeField(verbose_name="Adding time", auto_now=True)
		# Set a foreign key to associate with StuClass
    # On delete = models.cascade means Association delete
    # If the class is deleted, the corresponding students will also be deleted
		forkey = models.ForeignKey(to=StuClass, on_delete=models.CASCADE)

After the field is created, add the field to the management background (it's provided by Django, and you don't need to write it yourself, isn't it convenient?)

Location: stu_test/app1/admin.py

from django.contrib import admin

# Import models is the field class we just wrote. We use. Models for the same level directory and asterisk for import
from .models import *
  
# Join the two tables we wrote
# Learn by rote from admin.site.register and find that there is no prompt in pycharm
admin.site.register(StuClass)
admin.site.register(Students)

Next, we will migrate the data and open Terminal (in the lower left corner of pycharm), as shown in the figure below

Here we need to note that in the box, djang Peng env is the virtual environment used

E:\django_test\stu_test is the current path

Enter the following code to migrate the file

python manage.py makemigrations

The following tips

The migration file is generated, and then the migration starts

Continue to enter the following code

python manage.py migrate

The tips are as follows:

The data has been migrated.

If we want to enter student information through the management background, then we need to create an administrator account. Enter the following code:

python manage.py createsuperuser

According to the prompt, we fill in the user name, email address and password at one time as shown in the figure:

The password I entered is 123456. It's too common. Do you want to use it.

Enter y here and enter. Just use this password. The administrator account is created successfully.

Next, we run the server and continue to enter the following code:

python manage.py runserver

The prompt is as follows:

Here, http://127.0.0.1:8000/ where 127.0.0.1 represents our local port, which is 8000.

The server will run. Next, open http://127.0.0.1:8000/admin (Note: the admin in the address is not our administrator's user name, but the address in the route. The location: stu_test/stu_test/urls.py by default, we will not modify it first)

Open as follows:

Enter our username and password, I'm admin and 123456

We will see the following figure:

Here you can see the two tables you created earlier,

Looking at is there something strange, the names of the two watches look very uncomfortable in English?

We open the previous models.py and modify the code as follows

from django.db import models


class StuClass(models.Model):
    class_stu = models.CharField(verbose_name="class", max_length=10, null=False, unique=True)
    add_time = models.DateTimeField(verbose_name="Adding time", auto_now_add=True)
    updata_time = models.DateTimeField(verbose_name="Adding time", auto_now=True)
    class Meta:
        verbose_name = "class"
        verbose_name_plural = verbose_name

class Students(models.Model):
    name = models.CharField(verbose_name="Full name", max_length=6, null=False)
    age = models.IntegerField(verbose_name="Age", null=False)
    genders = (
        (0,"male"),
        (1,"female"),
    )
    gender = models.IntegerField(verbose_name="Gender", choices=genders)
    add_time = models.DateTimeField(verbose_name="Adding time", auto_now_add=True)
    updata_time = models.DateTimeField(verbose_name="Adding time", auto_now=True)
		forkey = models.ForeignKey(to=StuClass, on_delete=models.CASCADE)
    class Meta:
    		# Change the name of the watch to student
        verbose_name = "Student"
					# We all know that in English, the plural is mostly followed by the word "s", if we don't write this sentence
          # The name will be student s
        verbose_name_plural = verbose_name

Save it and the server will restart automatically. Let's refresh the previous page:

Is it convenient to watch?

Next, we add data. First, we add several classes, such as class 1, class 2 and class 3

I won't go into details here. It's all in Chinese. I believe it will be added.

After adding, we enter the class, as shown in the figure:

What's all this? It seems like a lot of work. Open the models.py file again and modify the following code:

from django.db import models


class StuClass(models.Model):
    class_stu = models.CharField(verbose_name="class", max_length=10, null=False, unique=True)
    add_time = models.DateTimeField(verbose_name="Adding time", auto_now_add=True)
    updata_time = models.DateTimeField(verbose_name="Adding time", auto_now=True)
    class Meta:
        verbose_name = "class"
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.class_stu

class Students(models.Model):
    name = models.CharField(verbose_name="Full name", max_length=6, null=False)
    age = models.IntegerField(verbose_name="Age", null=False)
    genders = (
        (0,"male"),
        (1,"female"),
    )
    gender = models.IntegerField(verbose_name="Gender", choices=genders)
    add_time = models.DateTimeField(verbose_name="Adding time", auto_now_add=True)
    updata_time = models.DateTimeField(verbose_name="Adding time", auto_now=True)
    forkey = models.ForeignKey(to=StuClass, on_delete=models.CASCADE)
    class Meta:
        verbose_name = "Student"
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name

We can see

# There are more in the class list:
def __str__(self):
				# self.class_stu
        # self represents the current class
        # Self.class'stu is the class'stu field under the current class
        # It's not hard to find that the class "stu" field enables us to define the class name
        return self.class_stu

# There are many students in the list:
# Why write it here? Because it will be like this when adding students
# You can not write first, and then you can write when you add students
# Add it here to reduce unnecessary duplication
def __str__(self):
				# Same as class
        return self.name

Save it. Let's refresh the next page, as shown in the figure

Isn't that weird, def str(self): let's just memorize it here

Next we add students. To draw inferences from one example, we should also add students. Now it's learning. There's no need to add so much. I've probably added some, as shown in the figure:

In this way, we input the data in the background. This is the end of this article. In the next article, we will talk about how to configure routes, create pages, and add, delete, modify and query. You can type it yourself first to add some impressions, which will make learning much faster.

It's been written all afternoon. It's time for dinner. I haven't eaten it all day. I'm not hungry. We should pay more attention to our health.

If you don't understand, you can leave a message or send a private message. Let's communicate with each other

Published 5 original articles, praised 0, visited 40
Private letter follow

Tags: Python Django Pycharm SQLite

Posted on Fri, 21 Feb 2020 06:30:14 -0500 by keyoung