1.Django基础
4.Django的安装
pip3 install django==1.11.1
所要使用到的命令
django-admin startproject xxx 创建项目 例如django-admin startproject day48 python manage.py startapp xxx #创建app 例如 python manage.py startapp app1 python manage.py runserver 127.0.0.1:8080 #启动项目 python manage.py makemigrations 生成同步数据库的脚本 python manage.py migrate 同步数据库 python manage.py createsuperuser创建用户名密码
当前目录下生成的项目
- manage.py ----- Django项目里面的工具,通过它可以调用django shell和数据库等。
- settings.py ---- 包含了项目的默认设置,包括数据库信息,调试标志以及其他一些工作的变量。
- urls.py ----- 负责把URL模式映射到应用程序。
访问http://127.0.0.1:8080/admin/
5.settings配置
STATICFILES_DIRS=( os.path.join(BASE_DIR,"statics"), )
wievs.py
from django.shortcuts import render ,HttpResponse # Create your views here. def index(request): return render(request,"index.html") def registe(request): if request.method=="POST": print(request.POST.get("user")) print(request.POST.get("age")) return HttpResponse("success") return render(request,"registe.html") def article(request,year,month): return HttpResponse("year:%s month:%s"%(year,month))
urls.py
from django.conf.urls import include, url from django.contrib import admin from app1 import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^index/', views.index), url(r'^article/(?P<year>\d{4})/(?P<month>\d{2})', views.article), url(r'^registe/',views.registe,name="reg") ]
registe.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% load staticfiles %} <title>Title</title> </head> <body> <form action="{% url "reg" %}" method="post"> {% csrf_token %} <p>姓名:<input type="text" name="user"></p> <p>年龄:<input type="text" name="age"></p> <p>爱好:<input type="checkbox" name="hobby" value="1">排球 <input type="checkbox" name="hobby" value="2">足球 <input type="checkbox" name="hobby" value="3">乒乓球 </p> <p><input type="submit" value="提交"></p> </form> </body> </html>
自定义
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter def filter_multi(x,y): print(x,y) return x*y
6.mysql的配置
django默认支持sqlite,mysql, oracle,postgresql数据库
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'books', #你的数据库名称 'USER': 'root', #你的数据库用户名 'PASSWORD': 'root', #你的数据库密码 'HOST': 'localhost', #你的数据库主机,留空默认为localhost 'PORT': '3306', #你的数据库端口 } }
settings.py同级的__init__里写入
import pymysql pymysql.install_as_MySQLdb()
创建项目
django-admin startproject mysite
创建项目的目录
mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py
manage.py 一个让你用各种方式管理 Django 项目的命令行工具
mysite/ 目录包含你的项目,它是一个纯 Python 包
mysite/__init__.py 一个空文件,告诉 Python 这个目录应该被认为是一个 Python 包
mysite/settings.py Django 项目的配置文件
mysite/urls.py Django 项目的 URL 声明,就像你网站的“目录”
mysite/wsgi.py 作为你的项目的运行在 WSGI 兼容的Web服务器上的入口
运行项目
python manage.py runserver
输出
erforming system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. 八月 01, 2018 - 15:50:53 Django version 2.0, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
运行 Django 命令行工具来创建数据库表
python manage.py migrate
创建应用
python manage.py startapp app01
目录
app01/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py
app01应用迁移
python manage.py makemigrations app01
运行python manage.py makemigrations 为模型的改变生成迁移文件
创建数据表
python manage.py migrate
这个 migrate
命令选中所有还没有执行过的迁移(Django 通过在数据库中创建一个特殊的表 django_migrations
来跟踪执行过哪些迁移)并应用在数据库上 - 也就是将你对模型的更改同步到数据库结构上
创建的各种 API
python manage.py shell
创建一个管理员账号
python manage.py createsuperuser
键入你想要使用的用户名,然后按下回车键:
Username: admin
然后提示你输入想要使用的邮件地址:
Email address: admin@example.com
最后一步是输入密码。你会被要求输入两次密码,第二次的目的是为了确认第一次输入的确实是你想要的密码。
Password: ********** Password (again): ********* Superuser created successfully.
打开浏览器输入 http://127.0.0.1:8000/admin/到登录页面
完整的settings.py(手动创建项目必备)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
""" Django settings for books project. Generated by 'django-admin startproject' using Django 1.11.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'u^-a2p3z&9q5%_1#q*$n9+3hriiw*vc^w6#y&p*7pbmm&bg+tk' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01.apps.App01Config', ] 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', ] ROOT_URLCONF = 'books.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , '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', ], }, }, ] WSGI_APPLICATION = 'books.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR,"static"), )