标签:build 心情 uname context fas efi doc like pps
MVC模式:
model:数据库
view:前端展示
controller:逻辑控制
MTV模式
model:数据库
view:逻辑控制
template:前端展示
flask,FastApi是轻量级服务端开发框架
Django是重量级服务端开发框架
ORM:封装了数据库操作
form:校验请求数据
安装Django:
pip install django==2.1 #指定版本安装,默认是安装最新版本
注意:最新版本的Django对mysql版本也有要求
1.创建项目命令:django-admin startproject ssz_django
2.启动项目命令:
python manage.py runserver 默认端口启动8000
python manage.py runserver 0.0.0.0:8002 指定端口启动,别人也可以访问
python manage.py runserver 127.0.0.1:8002 指定端口启动,只能自己访问
3.创建子模块:python manage.py startapp user
4.创建表结构:
python manage.py makemigrations
python manage.py migrate
5.查询命令
python manage.py --help
File--New Project--Django
Tools--Run manage.py Task 进入命令行
startapp user #创建user子模块
该文件是用来配置url的
1 from django.contrib import admin 2 from django.urls import path 3 from user import views #引入模块 4 5 urlpatterns = [ 6 path(‘admin/‘, admin.site.urls), 7 path(‘index/‘, views.user_info), 8 path(‘welcome/‘,views.welcome), 9 path(‘‘,views.index),#配置url 10 ]
该文件是配置文件,数据库等配置
1 import os 2 3 # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 4 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 5 6 7 # Quick-start development settings - unsuitable for production 8 # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 9 10 # SECURITY WARNING: keep the secret key used in production secret! 11 SECRET_KEY = ‘6ui+975ck&h4o8f9ga!lnz%j7u&se&-%69&-(h(4!-q4n80y9c‘ 12 13 # SECURITY WARNING: don‘t run with debug turned on in production! 14 DEBUG = True 15 16 ALLOWED_HOSTS = [] 17 18 19 # Application definition 20 21 INSTALLED_APPS = [ #加增加的应用 22 ‘django.contrib.admin‘, 23 ‘django.contrib.auth‘, 24 ‘django.contrib.contenttypes‘, 25 ‘django.contrib.sessions‘, 26 ‘django.contrib.messages‘, 27 ‘django.contrib.staticfiles‘, 28 ‘user‘, 29 ‘test_tools‘, 30 ‘case‘ 31 ] 32 33 MIDDLEWARE = [ 34 ‘django.middleware.security.SecurityMiddleware‘, 35 ‘django.contrib.sessions.middleware.SessionMiddleware‘, 36 ‘django.middleware.common.CommonMiddleware‘, 37 ‘django.middleware.csrf.CsrfViewMiddleware‘, 38 ‘django.contrib.auth.middleware.AuthenticationMiddleware‘, 39 ‘django.contrib.messages.middleware.MessageMiddleware‘, 40 ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘, 41 ] 42 43 ROOT_URLCONF = ‘sky.urls‘ 44 45 TEMPLATES = [ 46 { 47 ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘, 48 ‘DIRS‘: [os.path.join(BASE_DIR,‘templates‘)],#指的是Django寻找html的目录 49 ‘APP_DIRS‘: True, 50 ‘OPTIONS‘: { 51 ‘context_processors‘: [ 52 ‘django.template.context_processors.debug‘, 53 ‘django.template.context_processors.request‘, 54 ‘django.contrib.auth.context_processors.auth‘, 55 ‘django.contrib.messages.context_processors.messages‘, 56 ], 57 }, 58 }, 59 ] 60 61 WSGI_APPLICATION = ‘sky.wsgi.application‘ 62 63 64 # Database 65 # https://docs.djangoproject.com/en/2.1/ref/settings/#databases 66 67 DATABASES = { 68 ‘default‘: { 69 ‘ENGINE‘: ‘django.db.backends.sqlite3‘, 70 ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘), 71 } 72 } 73 74 75 # Password validation 76 # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 77 78 AUTH_PASSWORD_VALIDATORS = [ 79 { 80 ‘NAME‘: ‘django.contrib.auth.password_validation.UserAttributeSimilarityValidator‘, 81 }, 82 { 83 ‘NAME‘: ‘django.contrib.auth.password_validation.MinimumLengthValidator‘, 84 }, 85 { 86 ‘NAME‘: ‘django.contrib.auth.password_validation.CommonPasswordValidator‘, 87 }, 88 { 89 ‘NAME‘: ‘django.contrib.auth.password_validation.NumericPasswordValidator‘, 90 }, 91 ] 92 93 94 # Internationalization 95 # https://docs.djangoproject.com/en/2.1/topics/i18n/ 96 97 #LANGUAGE_CODE = ‘en-us‘ #英文 98 LANGUAGE_CODE = ‘zh-Hans‘#中文 99 100 TIME_ZONE = ‘Asia/Shanghai‘#时区 101 102 USE_I18N = True 103 104 USE_L10N = True 105 106 USE_TZ = False#True:往数据库里插数据,用的标准时区的时间 107 108 109 # Static files (CSS, JavaScript, Images) 110 # https://docs.djangoproject.com/en/2.1/howto/static-files/ 111 112 STATIC_URL = ‘/static/‘ 113 114 STATICFILES_DIRS = ( 115 os.path.join(BASE_DIR,‘static‘), 116 ) 117 118 MEDIA_ROOT = os.path.join(BASE_DIR,‘images‘)#图片的总目录 119 MEDIA_URL = ‘/images/‘
该文件是用来部署用的
项目管理文件
操作数据库文件
建单表代码
1 from django.db import models 2 3 # Create your models here. 4 class Category(models.Model): 5 name = models.CharField(verbose_name=‘分类名称‘,max_length=20,unique=True) 6 create_time = models.DateTimeField(verbose_name=‘创建时间‘,auto_now_add=True) 7 update_time = models.DateTimeField(verbose_name=‘修改时间‘,auto_now=True) 8 class Meta: 9 db_table = ‘category‘ #指定表名 10 verbose_name = ‘分类‘ 11 verbose_name_plural = verbose_name 12 ordering = [‘-create_time‘,‘name‘] #排序,默认是升序,-是降序
建有外键的表的代码
1 class Article(models.Model): 2 title = models.CharField(verbose_name=‘标题‘,max_length=50) 3 content = models.TextField(verbose_name=‘文章内容‘) 4 category = models.ForeignKey(Category,on_delete=models.DO_NOTHING,db_constraint=False,verbose_name=‘分类‘) 5 #建外键,on_delete=models.DO_NOTHING:当分类被删除时,文章不被影响 6 #db_constraint = False:不会在表中建立真实的外键关系 7 8 img = models.ImageField(upload_to=‘article‘,verbose_name=‘文章图片‘,blank=True)#图片存放的文件夹 9 create_time = models.DateTimeField(verbose_name=‘创建时间‘, auto_now_add=True) 10 update_time = models.DateTimeField(verbose_name=‘修改时间‘, auto_now=True) 11 class Meta: 12 db_table = ‘article‘ #指定表名 13 verbose_name = ‘文章‘ 14 verbose_name_plural = verbose_name 15 ordering = [‘-create_time‘] #排序,默认是升序,-是降序
代码写好后,分别执行以下命令,就可以生成表结构
python manage.py makemigrations
python manage.py migrate
Django 内嵌了sqllite,默认就是将表创建在sqllite中
如果想要连接mysql等其他数据库,需要自己在settings.py文件中配置
关联删除模式:
#外键删除操作模式 #models.DO_NOTHING:不受任何影响 #models.CASCADE:关联的数据也会被删除,分类被删除,引用分类的文章也会被删除 #models.SET:传入一个方法名,用方法返回值 #models.SET_DEFAULT:删除了,设置为默认值,要该字段有默认值 #models.SET_NULL:删除了,直接设置为空,要该字段可为空 #models.PROTECT#受保护,不能删除,只要这个分类下有文章,就不能删除这个分类
是用来做逻辑处理的文件
1 from django.http import HttpResponse 2 from django.shortcuts import render 3 from . import models 4 5 # Create your views here. 6 7 def user_info(request): 8 s = ‘你好‘ 9 return HttpResponse(s)#返回的是字符串 10 11 12 def welcome(request): 13 username = ‘谢谢啦dddd‘ 14 # f = open(‘G:\\pythonWorkspace\\day018\\sky\\templates\\welcome.html‘,encoding=‘utf-8‘) 15 # content = f.read() 16 # new_content = content.replace(‘{{ uname }}‘,username) 17 # return HttpResponse(new_content) 18 # render 就等于上面的一系列操作 19 return render(request,‘welcome.html‘,{‘uname‘:username}) 20 21 22 def index(request): 23 categories = models.Category.objects.all() 24 articles = models.Article.objects.all() 25 return render(request,‘index.html‘,{‘categories‘:categories,‘articles‘:articles})
1 #第一种方式:增加 2 category = models.Category(name=‘mysql‘) 3 category.save() 4 5 #第二种方式:增加 6 models.Category.objects.create(name=‘心情日记‘)
1 #修改 2 c1 = models.Category.objects.get(id=1) 3 c1.name = ‘Java‘ 4 c1.save()#单个数据修改 5 6 #多个数据修改 7 q = models.Category.objects.filter(name=‘python‘) 8 q.update(name=‘Python1‘)
1 #查询 2 #只能返回一条数据,如果返回多条数据会报错 3 #如果指定的条件查询不到数据,也会报错 4 c1 = models.Category.objects.get(name=‘linux‘,id=2) 5 6 #可以返回多条数据,返回结果为list,如果查询不到结果,则返回空 7 query_set = models.Category.objects.filter(name=‘python‘,id=8) 8 print(query_set.first().name) 9 print(query_set[1]) 10 print(query_set) 11 12 #查询所有的数据 13 categories = models.Category.objects.all()
1 #删除 2 #单条数据删除 3 c1 = models.Category.objects.get(id=1) 4 c1.delete() 5 6 #多条数据删除 7 q = models.Category.objects.filter(name=‘Python1‘) 8 q.delete()
标签:build 心情 uname context fas efi doc like pps
原文地址:https://www.cnblogs.com/cjxxl1213/p/13510309.html