1.创建新项目 把静态文件夹的名字放在settings文件里面
STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,"static") ]
2.创建表的时候User表继承AbstractUser时 settings文件要加上
AUTH_USER_MODEL="app01.UserInfo"
class UserInfo(AbstractUser): """ 用户信息 """ nid = models.AutoField(primary_key=True) telephone = models.CharField(max_length=11, null=True, unique=True) avatar = models.FileField(upload_to='avatar/', default="avatar/default.png") create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True) img = models.CharField(max_length=128,default='/static/img/default.gif') blog = models.OneToOneField(to='Blog', to_field='nid', null=True, on_delete=models.CASCADE)
3.若是用的mysql数据库则在跟项目名同名的文件夹中的init文件加上下面这句话
import pymysql pymysql.install_as_MySQLdb()
并且在settings文件中修改DATADASES的信息 比如:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'blog', # 要连接的数据库,连接前需要创建好 'USER':'root',# 连接数据库的用户名 'PASSWORD':'', # 连接数据库的密码 'HOST':'127.0.0.1',# 连接主机,默认本级 'PORT':3306 # 端口 默认3306 } }
4.在有form表单时,想通过点击事件发送ajax请求,这时候切记把type写成button
5.自己写的中间件记得在settings中注册
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'app01.middlewares.MD2', # 记得注册 ]
6.如何在Django项目中写个脚本来做测试,比如我们最常做的写脚本测试自己的ORM查询对不对。
这时候我们就要仿照项目中的manage.py 文件来写自己的脚本
那我们呢不妨先来看看manage.py的写法
1 #!/usr/bin/env python 2 import os 3 import sys 4 5 if __name__ == "__main__": 6 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "about_drf.settings") 7 try: 8 from django.core.management import execute_from_command_line 9 except ImportError: 10 # The above import may fail for some other reason. Ensure that the 11 # issue is really that Django is missing to avoid masking other 12 # exceptions on Python 2. 13 try: 14 import django 15 except ImportError: 16 raise ImportError( 17 "Couldn't import Django. Are you sure it's installed and " 18 "available on your PYTHONPATH environment variable? Did you " 19 "forget to activate a virtual environment?" 20 ) 21 raise 22 execute_from_command_line(sys.argv)
那我们就来仿照写一个check_test.py
1 import os 2 3 if __name__ == "__main__": 4 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "about_drf.settings") 5 import django 6 django.setup() 7 #######上面时固定格式下面开始写脚本########## 8 from app01 import models #这里一定把models引用过来,这样可以拿到表结构,然后做查询 9 import datetime 10 11 15 query_set = models.Article.objects.all().values("id", "title", "create_time", "type", "school__name") 16 17 obj = models.Article.objects.first() 18