1.django命令方式创建项目
#1.创建django项目 django-admin startproject sky(项目名称,随便写)
#2.启动项目(3种启动方式),启动后访问url,能访问说明项目创建成功了 #默认端口启动方式,url为:http://127.0.0.1:8000/ python3 manage.py runserver #指定端口启动方式,url为:http://127.0.0.1:8002/ python3 manage.py runserver 127.0.0.1:8002 ##默认端口启动方式,任何人都可以访问,url为:http://ip:8000/ python3 manage.py runserver 0.0.0.0:8002/
#3.项目中创建子应用(一般会创建case、test_tools、user等子应用) python3 manage.py startapp user
python3 manage.py startapp case
python3 manage.py startapp test_tools
#4.创建如下文件夹(注:是文件夹,不是子应用) templates文件夹:存放html文件 (index.html等) static文件夹:存放css、js、img文件夹 images文件夹:下载的图片存放的目录
#5.修改配置文件(位置:sky->sky->settings.py文件) #将创建的子应用添加到配置文件中 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'user', 'case', 'test_tools' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')],#指的django寻找html模板的目录 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LANGUAGE_CODE = 'zh-Hans'#改成中文的 TIME_ZONE = 'Asia/Shanghai'#改要不然时间就标准时区了 USE_TZ = False#改,要不然数据库还是标准时区
#static文件夹下存放所有静态文件,如css,js,image STATIC_URL = '/static/' #因为返回的是一个list,所以要用元组方式 STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) #下载的图片存放的位置 MEDIA_ROOT = os.path.join(BASE_DIR,'images') MEDIA_URL = '/images/'
#6.创建表(位置:sky->user->migrations->models.py) from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(verbose_name='分类名称',max_length=20,unique=True) create_time = models.DateTimeField(verbose_name='创建时间',auto_now_add=True) update_time = models.DateTimeField(verbose_name='修改时间',auto_now=True) class Meta: db_table = 'category' #创建表的时候表名 verbose_name = '分类' verbose_name_plural = verbose_name ordering = ['-create_time','name']#按创建时间倒叙排序,或按名称升序排序 def category_fun(): return 883 class Article(models.Model): title = models.CharField(verbose_name='标题', max_length=25) # varchar content = models.TextField(verbose_name='文章内容') img = models.ImageField(upload_to='article', blank=True) category = models.ForeignKey(Category, on_delete=models.SET(category_fun), #cascade db_constraint=False,verbose_name='分类') #CASCADE,关联的数据也会被删除 #models.PROTECT #受保护,不能删,只要这个分类下面有文章,那么这个分类就不能被删 # models.DO_NOTHING #什么也不再 #models.SET_NULL 设置成空,需要这个字段可以为空 # models.SET_DEFAULT,设置成这个字段的默认值,需要这个字段有默认值 # models.SET #传入一个方法名,用方法返回值 #https://www.cnblogs.com/zhangqunshi/p/6953915.html 外键on_delete选项 #db_constraint=False,不会真的在表里面创建外键关联 create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True) update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True) class Meta: db_table = 'article' # 创建表的时候表名 verbose_name = '文章' verbose_name_plural = verbose_name ordering = ['-create_time']
#7.生成表结构 python3 manage.py makemigrations #8.同步表结构到数据库 python3 manage.py migrate4.连接(就可以链接上创建的数据库了),库里面可以看到刚才创建的article和category两张表
以上执行成功后就可以链接数据库查看新建的表两张表了:
链接方式(我使用的是navicat工具):
1.链接名:django(这个是自己随便起的数据库名称)
2.类型:现有数据库文件
3.数据库文件:
/Users/wangxiaoyu/PycharmProjects/python_automated_development/yzh/day18/sky/db.sqlite3
#9.可以往表里添加一些数据(位置:sky->user->migrations->tests.py) from django.test import TestCase import os,django # Create your tests here. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sky.settings') django.setup()#注意添加的位置 from user import models #新增两种方式 # category = models.Category(name='python') # category.save() # models.Category.objects.create(name='Linux') models.Category.objects.create(name='Aix') models.Category.objects.create(name='java') models.Category.objects.create(name='python') models.Category.objects.create(name='shell') c = models.Category.objects.get(id='7') a = models.Article.objects.create(title='python 1天速成',content='逗你玩~',category=c)#直接写c a = models.Article.objects.create(title='python 15天速成',content='还是逗你玩~',category_id=7)#如果知道id的话可以直接写id a = models.Article.objects.create(title='python 30天速成',content='别想了~',category_id=7) #查pwdpwdcdcd # c1 = models.Category.objects.get(name='Aix',id=3)#只能返回一条数据,查询不到或查询的数据有多条都会报错 # print(c1.name) # a = models.Article.objects.get(id=1) # print(a.title) # print(a.category.name) # quer_set = models.Category.objects.filter(name='Aix') # c1 = quer_set[0] # print(c1.name) #删 # d =models.Category.objects.filter(name='Aix') # d.delete() #改 # m =models.Category.objects.filter(name='python') # m.update(name='windows')
#10.添加逻辑代码(位置:sky/user/views.py) from django.shortcuts import render,HttpResponse from . import models # Create your views here. # def user_info(request):#直接返回数据方式 # s = '你好' # return HttpResponse(s) # def welcome(request):#返回页面方式 # username = 'wxy' # return render(request,'welcome.html',{'username':username}) def index(request): categories = models.Category.objects.all()#获取category表中所有数据 articles = models.Article.objects.all()#获取article表中所有数据 return render(request,'index.html',{'categories':categories,'articles':articles})
#11.配置跳转url(位置:sky/sky/urls.py) from django.contrib import admin from django.urls import path from user import views urlpatterns = [ path('admin/', admin.site.urls), # path('index/', views.user_info), # path('welcome/', views.welcome), path('', views.index) ]
#12.修改index页面(sky/templates/index.html,部分代码展示)class="summary-list"> {% for article in articles %}class="media mb-1 mb-sm-2 p-2 p-lg-3">{% endfor %}class="align-self-center mr-2 mr-lg-3 w-25 modal-open"> "./detail.html" target="_blank"> class="w-100 article-img" src="https://tendcode.com/cdn/article/191029/python_shell.png" alt="{{ article.title }}">class="media-body">class="text-muted mb-2 f-12"> class="avatar" src="https://tendcode.com/media/avatar/2019/07/27/91ef76c6a7efce1b99717f97a851f3deb48f6510.png" alt="Hopetree"> Hopetree class="fa fa-calendar-times-o ml-2 mr-1">{{ article.create_time }}class="mt-0 font-weight-bold text-info f-17"> "/article/yaml_and_jinja2/" target="_blank">{{ article.title }}
class="d-none d-sm-block mb-2 f-15">{{ article.content }}
class="text-muted mb-0 f-12"> class="cate" href="/category/hello-python/" title="查看当前分类下更多文章"> class="fa fa-book mr-1">{{ article.category.name }} class="fa fa-eye ml-2 mr-1">226 "/article/yaml_and_jinja2/#comment-block" target="_blank" title="查看文章评论"> class="fa fa-comments ml-2 mr-1">8class="card border-0 rounded-0 px-3 mb-2 mb-md-3" id="category-card">class="card-header bg-white px-0"> class="fa fa-book mr-2 f-17">文章分类class="list-group list-group-flush f-16"> {% for category in categories %}
- class="list-group-item d-flex justify-content-between align-items-center pr-2 py-2"> class="category-item" href="./category.html" title="查看【{{ category.name }}】分类下所有文章">{{ category.name }} class="badge text-center" title="当前分类下有6篇文章">6
{% endfor %}
访问页面: