Django 4.0 Document Learning (1)

This series of articles is based on the official website documentation of Django 4.0 version learning
using development tools for pycharm

> python -m django --version
4.0

Write your first Django app, Part 1

create project

Run in pycharm terminal window

django-admin startproject mysite

insert image description here
The following files will be generated in the current project working directory
insert image description here

  • The outermost mysite/root directory is just the container of the project, and the name of the root directory has no effect on Django, and can be renamed to any name.
  • manage.py: A command-line tool that lets you manage Django projects in various ways.
  • The directory one level inside mysite/contains your project, which is a pure python package.
  • mysite/__init__.py: An empty file that tells Python that this directory should be considered a Python package.
  • mysite/settings.py: The configuration file for the django project.
  • mysite/urls.py: The URL declaration of the django project, just like the directory of your website.
  • mysite/asgi.py: Serves as the entry point for your project running on an ASGI-compatible web server.
  • mysite/wsgi.py: as the entry point for your project running on a WSGI-compliant web server.

Simple server for development

Make sure your Django project is really created successfully.
Go into the outermost mysite/ directory and run:

> cd .\mysite\ 
> python manage.py runserver

Seeing the following output indicates that the Django project is successfully created, ctrl+c ends the operation, and
insert image description here
the browser opens http://127.0.0.1:8000/
insert image description here
. By default, the runserver command will set the server to listen on port 8000 of the internal IP of the machine.
If changes are required, run

python manage.py runserver 8080

Rerun and python manage.py runserveryou'll see the link change tohttp://127.0.0.1:8080/

create application

Django comes with a tool that can help you generate the basic directory structure of the application.
The application name is arbitrary

> python manage.py startapp polls

insert image description here

write the first view

polls/views.py

from django.http import HttpResponse
def index(request):
    return HttpResponse("Hello,world.You're at the polls index.")

This is the simplest view in Django. To see the effect, we need to map a URL to it - that's why we need URLconf.

In order to create a URLconf, a new urls.py file needs to be created in the polls directory.
polls/urls.py

from django.urls import path
from . import views
urlpatterns=[
    path('',views.index,name='index'),
]

The next step is to specify the polls.urls module we created in the root URLconf file. Insert an include() into the urlpatterns list of the mysite/urls.py file.
mysite/urls.py

from django.contrib import admin
from django.urls import include,path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

Verify that it is working

python manage.py runserver
http://127.0.0.1:8000/polls

insert image description here

Write your first Django app, Part 2

mysite/settings.py some configuration

#LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-Hans'#中文

#TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'#中国时区

database configuration

mysite/settings.py
Django's default configuration of the sqlite3 database
'db.sqlite3'will store the database file in the root directory of the project.
insert image description here

DATABASES = {
    
    
    'default': {
    
    
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

If you configure the MySQL database, you must first enter the MySQL command line interface to build a database for the project, such as:

create database xxx数据库名;
DATABASES = {
    
    
    'default': {
    
    
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'xxx数据库名',
        'USER': '用户名',
        'PASSWORD': '密码',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

create model

The first step in writing a database-driven web application in Django is to define the model - that is, the database schema design and other metadata attached to it.
The official website tutorial to create polls application is a voting application that creates two models: Question and Choice. The Question model includes a description of the question and when it was posted. The Choice model has two fields, the option description and the current number of votes. Each option belongs to a question.
polls/models.py

from django.db import models
class Question(models.Model):
    question_text = models.CharField(max_length=200)#CharField字符字段
    pub_date=models.DateTimeField('date published')#DateTimeField日期时间字段
class Choice(models.Model):
    question=models.ForeignKey(Question,on_delete=models.CASCADE)
    choice_text=models.CharField(max_length=200)
    votes=models.IntegerField(default=0)

activation model

First, we have to install the polls application into our project and add it to the
mysite/settings.py INSTALLED_APPS list
'polls.apps.PollsConfig'

> python manage.py makemigrations polls

Migrations for 'polls':
  polls\migrations\0001_initial.py
    - Create model Question
    - Create model Choice

By running the makemigrations command, Django will detect your changes to the model files and store the changes as a migration.
Migrations are Django's way of storing changes to model definitions (that is, your database structure). It is stored in polls/migrations/0001_initial.py.
insert image description here
See which SQL statements will be executed by the migration command. The sqlmigrate command accepts a migration name and returns the corresponding SQL:

> python manage.py sqlmigrate polls 0001

insert image description here
Run the migrate command to create a data table for the newly defined model in the database:

> python manage.py migrate

Migration is a very powerful feature that allows you to continuously change the database structure during development without having to delete and create tables again. Changing the model requires these three steps:

  • Edit the models.py file and change the model.
  • Run python manage.py makemigrations to generate migration files for model changes.
  • Run python manage.py migrate to apply database migrations.

Initial test API

Open the python command line

python manage.py shell

Try the database API

>>> from polls.models import Choice,Question
>>> 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(2023, 3, 17, 7, 30, 17, 75596, tzinfo=datetime.timezone.utc)
>>> q.question_text="What's up?"
>>> q.save()
>>> Question.objects.all()                                             
<QuerySet [<Question: Question object (1)>]>

<Question: Question object (1)>It doesn't help us understand the details of this object. Fix this by editing the code for the Question model (located in polls/models.py ). Add str () method to Question and Choice. It is very important to add the str
() method to the model , which not only brings convenience to your use on the command line, but also uses this method to represent objects in the admin automatically generated by Django. Then add a custom method to this model: polls/models.py

import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
    question_text = models.CharField(max_length=200)#CharField字符字段
    pub_date=models.DateTimeField('date published')#DateTimeField日期时间字段
    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

quit()Exit the command line. Open the Python interactive command line again with python manage.py shellthe command .

>>> from polls.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(pk=1)
<Question: What's up?>
>>> q=Question.objects.get(pk=1)
>>> q.was_published_recently()
True
>>> 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
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
(1, {
    
    'polls.Choice': 1})

quit()Exit.

Introducing the Django admin page

Create an administrator account python manage.py createsuperuser
password I wrote admin

> python manage.py createsuperuser
用户名 (leave blank to use 'dell'): admin
电子邮件地址: admin@example.com
Password: 
Password (again):
密码跟 用户名 太相似了。
密码长度太短。密码必须包含至少 8 个字符。
这个密码太常见了。
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

Start the development server python manage.py runserver
, log http://127.0.0.1:8000/admin
insert image description here
in, and add polls/admin.py
insert image description here
to the management page

from django.contrib import admin
from .models import Question
admin.site.register(Question)

Refresh the page
insert image description here
to experience the convenient management function
insert image description here
insert image description here
insert image description here
insert image description here
and see the modification history
insert image description here

Guess you like

Origin blog.csdn.net/weixin_46322367/article/details/129618100