老男孩S16期的Django笔记(二)
day59-002 内容回顾.mp4
urls.py
点击查看代码
from django.conf.urls import url
from django.contrib import admin
from django.shortcuts import render
# day59-002 内容回顾
def login(request):
return render(request, 'login.html')
urlpatterns = [
url(r'^login/$', login),
# url(r'^index/$', index),
]
settings.py
点击查看代码
"""
Django settings for mysite 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 = 'i(jw%dl9a%cfxca5$5rb(1)1()$w*me4c+^or$@bxbs2el*v2e'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
# 我这个项目有哪些app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config', # 告诉Django我自己新建了一个名叫app01的应用
# 'app01'
]
# 中间件相关的配置
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 = 'mysite.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 = 'mysite.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'),
}
}
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.mysql', # 连接数据库的类型
# 'NAME': 'mysite', # 数据库名
# 'HOST': '127.0.0.1', # 数据库主机地址
# 'PORT': 3306, # 数据库的端口
# 'USER': 'root',
# 'PASSWORD': '',
# }
# }
# 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'),
]
# python manage.py runserver 127.0.0.1:8000
day59-003 登录示例.mp4
预期功能:当点击登录表单的提交按钮后,页面访问url为/yingying/ 请求方法POST ,页面回显“可以”字符串(无样式),controller层的方法定义在views.py文件。
1. form表单提交数据的三个要素
1. form标签必须要有action和method属性
2. 所有获取用户输入的标签必须放在form表单中,必须要有name属性
3. 必须要有submit按钮
表单页面文件修改action
<form class="form-horizontal" action="/yingying/" method="post">
views.py
from django.shortcuts import render, HttpResponse
# day59-003 登录示例
def login(request):
return render(request, 'login.html')
def yingying(request):
return HttpResponse('可以')
urls.py
from django.conf.urls import url
from django.contrib import admin
from django.shortcuts import render
from . import views
# day59-003 登录示例
urlpatterns = [
url(r'^login/$', views.login),
url(r'^yingying/$',views.yingying)
]
2. Django 基础必会三件套
from django.shortcuts import HttpResponse, render, redirect
1. HttpResponse
返回一个指定的字符串时
2. render
返回一个HTML文件
3. redirect
跳转
3. request相关的属性
1. request.method --> 返回的是请求的方法(全大写):GET/POST ...
2. request.GET --> 取得是URL里面的参数,类似于字典的数据结构
3. request.POST --> post提交的数据,类似于字典的数据结构
返回一个302重定向页面跳转
views.py
from django.shortcuts import render, HttpResponse, redirect
# day59-003 登录示例
def login(request):
return render(request, 'login.html')
def yingying(request):
#控制台打印一下
# print(request.POST)
email = request.POST.get('email')
pwd = request.POST.get('pwd')
print(email, pwd)
if email == '1@1.com' and pwd =='123':
# 登陆成功
# 重定向到我的CSDN博客
return redirect('https://blog.csdn.net/qq_40993412')
else:
# 登陆失败
# 提示用户账号或密码错误
pass
return HttpResponse('可以')
4. Django的模板语言
{{ 变量名 }}
6. Django项目app --> 项目中又分了一级Python包,不同的功能放到不同的包里面
1. 创建app
python manage.py startapp app01
2. 告诉Django创建了一个app
在settings.py找那个的INSTALLED_APPS中添加新创建的app
命令行创建package存放views.py
python manage.py startapp app01
在settings.py找那个INSTALLED_APPS中添加
使用ORM框架操作SQL数据库
1. 手动创建一个数据库可用连接
2. 告诉Django连哪个数据库
DATABASES = {
'default': {
点击查看代码
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 连接数据库的类型
'NAME': 'mysite', # 数据库名
'HOST': '127.0.0.1', # 数据库主机地址
'PORT': 3306, # 数据库的端口
'USER': 'root',
'PASSWORD': '',
}
}
https://www.cnblogs.com/chenyuebai/p/7821996.html
python3.6 mysql:5.7 pymysql:0.7.11
pip install pymysql==0.7.11 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install mysqlclient==1.3.14 -i https://pypi.tuna.tsinghua.edu.cn/simple
3. 用什么连数据库?
利用第三方的包,比如第三方包:pymysql和MySQLdb
告诉Django用pymysql模块代替默认的MySQLdb去连接MySQL数据库
和settings.py同级的__init__.py文件,写上:
import pymysql
pymysql.install_as_MySQLdb()
__init__.py
import pymysql
pymysql.install_as_MySQLdb()
4. 在app/models.py的文件中创建类
类必须继承models.Model
5. 另外两个命令
1. python manage.py makemigrations --> 找个小本本把models.py的变更记录一下
2. python manage.py migrate --database=mysql --> 把上面的变更记录翻译成SQL语句,去数据库执行
从数据库里查询获取email和pwd的值
from app01.models import User
# day59-003 登录示例
def login(request):
error_msg = ''
#需要判断
if request.method == 'POST':
# 如果是第二次来,表示填完了要给我发数据了 ---> POST
email = request.POST.get('email')
pwd = request.POST.get('pwd')
print(email, pwd)
# if email == '1@1.com' and pwd =='123':
ret = User.objects.filter(email = email , pwd=pwd)
if ret:
# 登陆成功
ssh连接服务器,进入mysql命令行
mysql -u root -p
参考资料: