current position:Home>Day 1: learn the Django framework of Python development

Day 1: learn the Django framework of Python development

2022-01-30 00:56:31 Job theory test

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Django Introduce

Django It's an open Source code Of Web Application framework , from Python It's written in . Adopted MTV Framework model of , The model M, View V And templates T. It was originally developed to manage news content based websites owned by Lawrence publishing group , That is CMS( Content management system ) Software . And in 2005 year 7 Month in BSD license Issue under . This framework is based on the gypsy of Belgium Jazz guitar hand Django Reinhardt Named after .2019 year 12 month 2 Japan ,Django 3. 0 Release  [1] .

---- From baidu baike

Start your Django The first step of the journey !

  1. Environment building :Python Distribution version anaconda Tools to manage local development environments
 If you don't want to install anaconda, You can use python -m venv to_path< route >, Creating a virtual environment 

 Switch to the development environment , The virtual environment will basically have a activate file <linux yes sh,win yes bat Extension >

 install Django edition , At present, it has reached 3.2.6 The development version of , Then you can choose the latest stable version :3.2.5.
 Copy code 
  • The first step is to install :pip install Django # Install the latest version by default

D:> django-admin -h # Check the help document before creating the project

Type 'django-admin help ' for help on a specific subcommand. 
Available subcommands: 
[django]
 check 
 compilemessages 
 createcachetable 
 dbshell 
 diffsettings 
 dumpdata 
 flush 
 inspectdb 
 loaddata 
 makemessages 
 makemigrations 
 migrate 
 runserver 
 sendtestemail 
 shell 
 showmigrations 
 sqlflush 
 sqlmigrate 
 sqlsequencereset 
 squashmigrations 
 startapp 
 startproject 
 test 
 testserver 
 Note  that  only Django core commands are listed as settings are not properly configured 
 (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either 
 define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before 
 accessing settings.).
 Copy code 
  • Step 2: create a project :

django-admin startproject myDjango

  • Step 3: create sub application : Enter the project first < There can be multiple sub applications in a project >

python manage.py startapp myapp

  • Step 4: create a model :
from django.db import models

# Create your models here.
class UserInfo(models.Model):
    
    name=models.CharField(max_length=10)
    age=models.IntegerField()
    addr=models.CharField(max_length=100)
    gender=models.BooleanField()
    birth=models.DateField()
    
    def __str__(self):
        return self.name
    
class ClassInfo(models.Model):
    
    teacher=models.CharField(max_length=10)
    class_room=models.IntegerField()
    book=models.CharField(max_length=20)
    
    def __str__(self):
        """ In order to be in admin The field is displayed in the background and overridden str,1.x, Chinese garbled code still needs encode("utf-8") transcoding """
        return self.teacher
 Copy code 
  • Step 5: generate the migration script

python manage.py makemigrations myapp

  • Step 6 execute the migration script

python manage.py migrate

  • Step 7 create an administrator account

python manage.py createsuperuser

  • Step 8 register admin

Register model class , If you want to manage foreground data through the background

from django.contrib import admin

from myapp.models import UserInfo, ClassInfo


# Register your models here.
class UserInfoAdmin(admin.ModelAdmin):
    #  This is displayed when registering for background editing ; Default full display 
    # fields = [ "name", "age", "gender", "addr", "birth"]
    list_display = ("id", "name", "age", "gender", "addr", "birth")

class ClassInfoAdmin(admin.ModelAdmin):
    # fields = [ "teacher", "class_room", "book"]
    list_display = ("id", "teacher", "class_room", "book")
    
admin.site.register(UserInfo, UserInfoAdmin)
admin.site.register(ClassInfo, ClassInfoAdmin)
 Copy code 
  • Step 9 enter the sub application views.py Create view
from django.shortcuts import render
from django.http.response import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse("Hello World!")
    
def detail(request):
    return render(request,template_name="myapp/detail.html",content={"list":range(10)})
 Copy code 
  • Step 10 configure urls, In the management background urls.py
from django.contrib import admin
from django.urls import path

# django1.1 After the version , String defined views are no longer supported 
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r"^$",views.index),
    path("detail/",views.detail),
]
#  stay 1.x Version USES url, Support absolute and regular matching ;3.x distinguish path and re_path
 Copy code 
  • Step 11 create a template file in the project root path :templates/myapp
<html>
<title></title>
<body>
<ul>
{% for info in infoList %}
<li>{{info}}</li>
{% endfor %}
</ul>
</body>
</html>
 Copy code 
  • The twelfth step settings Set up
# myapp  Need to be in settings/INSTALLED_APPS  Additional application 
INSTALLED_APPS=["...","...",
# Own application 
"myapp",]

# admin The Chinese prompt area is displayed in the background 
LANGUAGE_CODE='zh-hans'
TIME_ZONE = 'Asia/Shanghai'

#  Total path configuration , Then go again. urls Find view 
ROOT_URLCONF='myDjango.urls'

#  Configure template path 
TEMPLATES
***
'DIRS': [os.path.join(BASE_DIR,"templates")], #  Be careful not to configure and view render The template path of is repeated 
***
 Copy code 

Expand :python manage.py shell

Access to sqlite3 Database operation

>>> from myapp.models import ClassInfo
>>> ci=ClassInfo()
>>> ci.teacher=" Miss Tang "
>>> ci.class_room=1001
>>> ci.book="java"
>>> ci.save() #  Remember to save after adding or modifying 
>>> ci.delete() #  Delete 
>>> ClassInfo.objects.all() #  Get all the data 
>>> ClassInfo.objects.get(id=1) #  The modified record is obtained first and then assigned and saved 
 Copy code 

Start the application :python manage.py runserver

visit :http://127.0.0.1:8000/admin/

copyright notice
author[Job theory test],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201300056293499.html

Random recommended