current position:Home>Zero basics Python web development online examination system - Introduction to Django framework project lesson 2 - model and management site (really take you on the road to play practical project development)

Zero basics Python web development online examination system - Introduction to Django framework project lesson 2 - model and management site (really take you on the road to play practical project development)

2022-02-02 12:21:19 huidaoli

The open source address of this article project :
https://codechina.csdn.net/csdn-django-web/django_kaoshi_demo

List of articles

Tips : Friends who need to download code can go to the above open source project library to pull code , Students who want to study together can join the project team to develop

Zero basis to learn Python Web Develop online examination system -Django Framework introduction project series ( Really take you on the road to play with actual combat project development )—— Catalog


Tips : If you like, please help with one button three times , Friends with questions can leave a message in the comment area .


Preface

The purpose of this series of articles :

Take you to zero Basics Python Web Development , And through real projects - Online examination system - To learn how to use Django frame .
Because there are more knowledge points , It's a lot of work , The chapters of the article are 7 Class hour , So the final function is not much , First realize the function of single topic selection ,
But the whole project came down , Will let you really start developing , Later, you can continue to add other functions according to this series of articles .


Let's not talk more nonsense , Let's start , If you have any questions on the way, please leave a message in the comment area or contact by private letter .

One 、 preparation

Installation of the development environment :

Python install :

The stairs are here :https://huidaoli.blog.csdn.net/article/details/121607251

Django install :

The stairs are here :https://huidaoli.blog.csdn.net/article/details/121607251
or https://huidaoli.blog.csdn.net/article/details/121465897

PyCharm install :

The stairs are here :https://huidaoli.blog.csdn.net/article/details/121465897

Environment installation verification

To verify Django If I can be Python distinguish , Can be in shell Input in python. And then in Python At the prompt , Try importing Django:

>>> import django
>>> print(django.get_version())
3.2

Yes, of course , You may also have other versions installed Django.

Two 、 Start developing

1. Database configuration

Now let's build a database , Create our first model , And use Django Automatically generated management page provided .

Now let's execute the order :

python manage.py migrate

Command execution result :

Windows PowerShell
 copyright  (C) 2016 Microsoft Corporation. All rights reserved .
PS F:\Gitee\django_kaoshi_demo\mysite> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

Students with questions can leave a message in the comment area

2. Creating models

Now let's define the model , That is, database structure design .

In the examination system, we need to create two models : Topics and options , It includes the description of the topic and the release time and other related contents .

Let's start editing kaoshi/models.py file :

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

Students with questions can leave a message in the comment area

3. Activate the model

We have created the model earlier , Now let's start creating a database for this application schema, That is to say, generate create table sentence , At the same time, create a database that can interact with each other api.

In the file mysite/settings.py in INSTALLED_APPS After adding a dotted path to the child .

INSTALLED_APPS = [
    'kaoshi.apps.KaoshiConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Let's run the following command to see :

python manage.py makemigrations kaoshi

The results will be output as follows :

PS F:\Gitee\django_kaoshi_demo\mysite> python manage.py makemigrations kaoshi
Migrations for 'kaoshi':
  kaoshi\migrations\0001_initial.py
    - Create model Question
    - Create model Choice

Next, we found one more file ,kaoshi/migrations/0001_initial.py

# Generated by Django 4.0 on 2021-12-15 06:58

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Question',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('question_text', models.CharField(max_length=200)),
                ('pub_date', models.DateTimeField(verbose_name='date published')),
            ],
        ),
        migrations.CreateModel(
            name='Choice',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('choice_text', models.CharField(max_length=200)),
                ('votes', models.IntegerField(default=0)),
                ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='kaoshi.question')),
            ],
        ),
    ]

From the above migration file, you can see the model migration record , Let's perform the migration and synchronize the database .

python manage.py sqlmigrate kaoshi 0001

The operation results are as follows :

PS F:\Gitee\django_kaoshi_demo\mysite> python manage.py sqlmigrate kaoshi 0001
BEGIN;
--
-- Create model Question
--
CREATE TABLE "kaoshi_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" d
atetime NOT NULL);
--
-- Create model Choice
--
CREATE TABLE "kaoshi_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer
NOT NULL, "question_id" bigint NOT NULL REFERENCES "kaoshi_question" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "kaoshi_choice_question_id_b57a701a" ON "kaoshi_choice" ("question_id");
COMMIT;

Now let's run migrate command , This completes the creation of the newly defined model data table .

python manage.py migrate

The operation results are as follows :

PS F:\Gitee\django_kaoshi_demo\mysite> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, kaoshi, sessions
Running migrations:
  Applying kaoshi.0001_initial... OK

By the above operation , We will synchronize the changes made to the model to the database structure .


4. Model API Use

Now let's start using the various... Created above api.
The command line is as follows :

python manage.py shell

Specific operation api command :

PS F:\Gitee\django_kaoshi_demo\mysite> python manage.py shell
Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from kaoshi.models import Choice, Question  # Import the model classes we just wrote.
>>> Question.objects.all()
<QuerySet []>
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
>>> q.save()
>>> q.id
1
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2021, 12, 15, 7, 11, 16, 571639, tzinfo=datetime.timezone.utc)
>>> q.question_text = "What's up?"
>>> q.save()
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>

Then let's work for Question and Choice increase str() Method :

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

Let's try adding a custom method to the model :

import datetime

from django.db import models
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

In order to see effect , Let's execute another interactive command :

python manage.py shell

The specific process is as follows :

PS F:\Gitee\django_kaoshi_demo\mysite> python manage.py shell
Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from kaoshi.models import Choice, Question
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]> >>> Question.objects.filter(id=1) <QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's up?>]> >>> from django.utils import timezone >>> current_year = timezone.now().year >>> Question.objects.get(pub_date__year=current_year) <Question: What's up?>
>>> Question.objects.get(id=2)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\django\db\models\manager.py", line 85, in manager_metho
d
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Administrator\AppData\Roaming\Python\Python39\site-packages\django\db\models\query.py", line 439, in get
    raise self.model.DoesNotExist(
kaoshi.models.Question.DoesNotExist: Question matching query does not exist.
>>> Question.objects.get(pk=1)
<Question: What's up?> >>> q = Question.objects.get(pk=1) >>> q.was_published_recently() True >>> q = Question.objects.get(pk=1) >>> q.choice_set.all() <QuerySet []> >>> q.choice_set.create(choice_text='Not much', votes=0) <Choice: Not much> >>> q.choice_set.create(choice_text='The sky', votes=0) <Choice: The sky> >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0) >>> c.question <Question: What's up?>
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
(1, {
    'kaoshi.Choice': 1})
>>>


Students with questions can leave a message in the comment area

5. Create an administrator account

In order to log in to the management background , Let's create an administrator account through the command line :
The order is as follows :

python manage.py createsuperuser

The creation process :

PS F:\Gitee\django_kaoshi_demo\mysite> python manage.py createsuperuser
Username (leave blank to use 'administrator'): admin
Email address: [email protected].com
Password:
Password (again):
The password is too similar to the username.
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

By the above operation , The user name and password have been created admin Account number of .


Students with questions can leave a message in the comment area

6. Start development server


Students with questions can leave a message in the comment area

7. Creating models

After the above operation , We have created a database , Data sheet , And created an administrator account , Now let's take a look at the backstage .
Start the server command :

python manage.py runserver

Startup results :

PS F:\Gitee\django_kaoshi_demo\mysite> python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
December 15, 2021 - 15:26:14
Django version 4.0, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/admin
Quit the server with CTRL-BREAK.

We began to visit http://127.0.0.1:8000/ have a look .
 Insert picture description here
The background home page after successful login :
 Insert picture description here


Students with questions can leave a message in the comment area ## 8. Add an application to the management background We didn't find our app in the background , Now let's add the application to the background .

Modify file kaoshi/admin.py

from django.contrib import admin

from .models import Question

admin.site.register(Question)

Refresh in the background , Applied :
 Insert picture description here


Students with questions can leave a message in the comment area ## 9. Use the test application function Now let's use our test function Find our test questions ![ Insert picture description here ](https://img-blog.csdnimg.cn/41063165254f467db8d147ea97d074ff.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAaHVpZGFvbGk=,size_20,color_FFFFFF,t_70,g_se,x_16)

Let's edit this topic :
 Insert picture description here


Students with questions can leave a message in the comment area

summary

That's all for today's content , Through the above learning, we learned to add database tables to our application , And set the management account , At the same time, I am familiar with the background management function , And simple editing of our examination questions , If you have any questions, you can leave a message in the comment area , See you next time .

copyright notice
author[huidaoli],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202021221160915.html

Random recommended