Django文件配置

创建项目的文件配置

1.创建app需要在配置文件里注册
2.模板路径配置: 创建templates文件夹 并 在settings注册
3.静态文件配置:STATIC_URL = '/static/'    一般不要改
创建一个static文件夹 一般不要改
STATICFILES_DIRS=[
  os.path.join(BASE_DIR, 'static')       创建的文件夹路径(可以写多个)
]
4.简单登录功能(例)

模板层

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {#  导入  #}
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    {#  样式布局  #}
    <link rel="stylesheet" href="/static/css/mycss.css">
    <title>登录</title>
</head>
<body>
<h1>登录</h1>
<div class="col-md-6 col-md-offset-3"><form action="" method="post">
    <p>用户名:<input type="text" name="name" class="form-control"></p>
    <p >
        密码:<input type="password" name="pwd" class="form-control">
    </p>
{# type是button,不会往后台提交数据 #} {# <input type="button" value="提交">#}
{# 这两种会往后台提交数据#}
<input type="submit" value="提交"> {# <button>提交</button>#} ​ </form></div> ​ ​ ​ </body> </html>

视图层

1 request.method  ----前台提交过来请求的方式
2 request.POST(相当于字典)----post形式提交过来的数据,(http请求报文的请求体重)
3 request.POST.get('name') ----推荐用get取值(取出列表最后一个值)
4 request.POST.getlist('name')-----取出列表所有的值_
5 前台get方式提交的数据,从request.GET字典里取
​
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        print(request.POST)
        name=request.POST.get('name')
        # name = request.POST['name']
        pwd = request.POST.get('pwd')
        user=models.User.objects.filter(name=name,pwd=pwd).first()
        if user:
            return redirect('登录成功')
        else:
            return HttpResponse('用户名密码错误')

连接数据库

cur.execute('select * from user where name=%s and password=%s ',[name,pwd])
5.get请求和post请求:

get:获取数据,页面,携带数据是不重要的数据(数据量有大小限制) post:往后台提交数据

6.新手三件套

1 render--返回页面 默认会去templates里找,注意路径

2 redirect--重定向

3 HttpResponse--字符串

本质:都是返回HttpResponse的对象

原文地址:https://www.cnblogs.com/zhangpang/p/9946457.html