MySql教程

Django三板斧演示、静态文件配置、form表单请求方法、pycharm与Django分别连接MySQL演示

本文主要是介绍Django三板斧演示、静态文件配置、form表单请求方法、pycharm与Django分别连接MySQL演示,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

昨日内容回顾

  • web应用
1.通过浏览器访问

2. web应用的优点:
	一个浏览器
	节省资源
	不用更新
    
3. 缺点:
	严格依赖服务端
	浏览器会出现兼容性问题
    
# python三大主流框架:
	Django框架
	flask
	tornado(异步高性能框架)
  • Django的MTV与MVC模式
# MTV:
	M	model
	T	template
	v	views
    
# MVC:
	M	model
	V	view
	C	controller
  • django下载安装
# 版本:
	django1.x
	django2.x
	django3.x
    
# 安装Django
	命令行:pip3 install django==1.1.1
    
# 创建项目
	1.命令行创建
		django-admin startproject 项目名	
        
	2.pycharm创建
'''django安装成功之后,会生成一个可执行文件,django-admin'''


# 两种方式创建的区别:
	1.pycharm创建有templates文件夹
    
	2.配置文件有区别
    
# 启动django项目
	1.命令行
		python3 manage.py runserver 127.0.0.1:8000
            
	2.pycharm启动
		点击绿色按钮
        
# 创建应用
	1.命令行:
		python3 manage.py startapp 应用名
        
	2.pycharm创建
'''应用创建完毕,一定要去配置文件注册应用'''

今日内容概要

  • django三板斧
  • 静态文件配置
  • request请求
  • form表单
  • pycharm连接MySQL
  • Django连接MySQL(重点)

内容详细

1. django三板斧

# 1.HttpResponse
	作为返回值 返回给浏览器了
   
	# 在 urls.py文件中添加:
"""   
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index)
]
"""  

	# 在 views.py文件中添加:
"""
from django.shortcuts import render,HttpResponse
import time
# Create your views here.

def index(request):  # 暂且记忆 index返回值是字符串类型
    print(123)
    return HttpResponse('HELLO DJANGO')  # 返回给浏览器了
"""
    
    
# 2.render
	# 在 urls.py文件中添加:
"""   
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index)
]
"""

	# 在 views.py文件中添加:
"""
from django.shortcuts import render, HttpResponse
import time

# Create your views here.

def index(request):
    print(123)
    ctime = time.strftime('%Y-%m-%d %X')
    a = 1
    b = 2
    print(locals())
    # return render(request, 'index.html', {'ctime11':ctime, 'a':1, 'b':2})  # 写法一
    return render(request, 'index.html', locals())  # 写法二
"""

	# 在templates文件夹下创建HTML文件
# HTML文件内容:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
    <h1>hello render!</h1>
    <h2>当前时间:{{ ctime01 }} </h2>
    <h2>当前时间:{{ a }} </h2> <!--大括号包大括号 模板语法-->
    <h2>当前时间:{{ b }} </h2> <!--大括号包大括号 模板语法-->

</body>
</html>
"""
{{}} 大括号包大括号 模板语法
{% %} 也是模板语法
"""
    
    
# 3.redirect
	# 在 urls.py文件中添加:
"""   
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index)
]
"""

	# 在 views.py文件中添加:
"""
from django.shortcuts import render, HttpResponse, redirect
import time

# Create your views here.

def index(request):
    print(123)
    ctime = time.strftime('%Y-%m-%d %X')
    a = 1
    b = 2
    print(locals())
    # return redirect('http://www.baidu.com')  # 返回值自动跳转
    return redirect('/admin/')  # 自动补充:ip+port/admin
"""


# 在settings.py文件中:
默认配置为:
	DEBUG = True  # 报错显示在浏览器页面上
	ALLOWED_HOSTS = []

如果改为:
	DEBUG = False  # 报错就不会再显示在浏览器页面了
	ALLOWED_HOSTS = ['*']

image

image

image

2. 静态文件配置

# 什么是静态文件
	css, js, jq, bootstrap, img...
    
# 静态文件的存储路径一般是static
	默认是没有这个文件夹的,所以需要我们自己手动创建出来这个文件夹
	static文件夹是在项目路径下的第一级文件目录
    
# 在static文件夹中还可以继续根据不同的功能进行划分
	js
	css  # 将CDN导入的CSS文件下载到本地 放置在该目录下
	lib
	img
    
# 在settings.py文件中:
"""
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),  # 这样一配置完成,静态路径的根就是static
]

此外还可以配置多个路径:
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),  
    os.path.join(BASE_DIR, 'static1'),  
    os.path.join(BASE_DIR, 'static2')
]
查找文件顺序为从上而下 找到为止
"""

# 新建HTML文件内容:{# 动态导入方法(推荐使用) #}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
{#    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>#}
{#    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">#}
{#    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>#}
{#    <link rel="stylesheet" href="/static/css/bootstrap.min.css">  {# 导入方法更改为本地导入 #}

    {# 动态导入方法(推荐使用) #}
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
</head>
<body>
    <div class="container">
        <div class="row">
            <h1 class="text-center">登录页面</h1>
            <form action="">
                <p>
                    <input type="text" name="username" class="form-control">
                </p>
                <p>
                    <input type="text" name="password" class="form-control">
                </p>
                <input type="submit" value="登录" class="btn-block btn-primary">
            </form>
        </div>
    </div>
</body>
</html>

image

image

3. form表单

# <form action=""> action参数内容:
	1.什么都不写,提交到当前页面
    
	2.全写:https://passport.baidu.com/v2/api/?login
        
	3.只写后缀
		/login/ => 浏览器会自动补全ip和端口
		http://127.0.0.1:8000/login/
                
# 请求方式:
	get 
		传参数方式:http://127.0.0.1:8000/login/?a=1&b=2&c=3
    
	post
    
	区别:
		get请求:
			1. get没有请求体
			2. 对数据大小的限制是4KB
			3. 不安全
            
		post请求:
			1. post才有请求体
			2. 对数据大小没有限制
			3. 安全
            
'''
	MySQL中可能会出现的安全问题:SQL注入
	前端当中可能会出现的安全问题:xss攻击
	django中会出现的安全问题:csrf跨站请求
'''


# 在settings.py文件中:
MIDDLEWARE = [
    'django.middleware.csrf.CsrfViewMiddleware',  # 在Django学习过程中 只要遇到csrf报错 就要将该行注释掉 最好不要删除 
]


# 在 views.py文件中添加:
"""
def login(request):
    # 1.判断请求方式
    print(request)  # <WSGIRequest: GET '/login/'> 结果为:GET请求
    print(request.method, type(request.method))  # GET / <class 'str'>  method意为:方法
    if request.method == 'POST':
        # 2.获取post请求方式的数据
        print(request.POST)  # <QueryDict: {'username': ['Deity-JGX'], 'password': ['123']}>
        print(request.POST.get('username'))  # Deity-JGX
        # get只能拿最后一个值
        print(request.POST.get('hobby'))  # 4 拿最后一个值
        print(request.POST.getlist('hobby'))  # ['1', '2', '3', '4'] 拿到所有的值

        username = request.POST.get('username')
        password = request.POST.get('password')

        if username == 'ly' and password == '123':
            return HttpResponse('登录成功')
        else:
            return HttpResponse('密码错误')
    return render(request, 'login.html')
"""


# 新建HTML文件内容:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
{#    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>#}
{#    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">#}
{#    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>#}
{#    <link rel="stylesheet" href="/static/css/bootstrap.min.css">  {# 导入方法更改为本地导入 #}

    {# 动态导入方法(推荐使用) #}
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
</head>
<body>
    <div class="container">
        <div class="row">
            <h1 class="text-center">登录页面</h1>
            <form action="" method="post">
                <p>
                    <input type="text" name="username" class="form-control">
                </p>
                <p>
                    <input type="password" name="password" class="form-control">
                </p>
                <input type="checkbox" name="hobby" value="1">
                <input type="checkbox" name="hobby" value="2">
                <input type="checkbox" name="hobby" value="3">
                <input type="checkbox" name="hobby" value="4">
                <input type="submit" value="登录" class="btn-block btn-primary">
            </form>
        </div>
    </div>
</body>
</html>

image

image

4. pycharm连接MySQL

如图操作:

image

image

image

5. django连接mysql

# 先在settings.py文件中修改以下信息:
DATABASES = {
    # 'default': {  # 注释掉该字典
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    # }

    'default':{  # 添加该字典
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db',  # 库名
        'HOST': '127.0.0.1',
        'POST': 3306,
        'USER': 'root',
        'PASSWORD': '123',
        'CHARSET': 'UTF8'
    }
}

# 如果此时直接启动项目 可能会遇到报错
'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?

原因是:
	django默认的操作mysql的模块是MySQLdb
'''
在python3.6版本以下,在任一__init__文件中 需要加入下面两句话:
如果你的解释器中没有pymysql模块 那就需要先安装pymysql
	pip3 install pymysql

如果有pymysql模块 直接写入下面代码:
	import pymysql
	pymysql.install_as_MySQLdb()
	
之后再重新启动项目
'''

image

这篇关于Django三板斧演示、静态文件配置、form表单请求方法、pycharm与Django分别连接MySQL演示的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!