一、Django表单(form)请求:

    打开的时候默认是GET请求,获取form表单的内容。

    点提交的时候是POST请求,提交form表单的内容。

    根据以上区别来编写获取表单内容:

from django.shortcuts import HttpResponsefrom django.shortcuts import render, redirectdef login(request):    # request包含用户提交的所有信息。    error_msg = ''    if request.method == 'POST':        user = request.POST.get('user', None)        //使用get方法获取'user'键值,如果没有user键,赋值None        pwd = request.POST.get('pwd', None)          //get方法里的user和pwd是form表单里input对象的name属性。        if user == '123' and pwd == '123456':            return redirect('http://www.baidu.com')        else:            error_msg = '用户名或密码错误'        return render(request, 'login.html', {'error_msg':error_msg})


二、{{key}}

        {{}}在html文件中指定key,通过views.py传递字典,html在客户端显示的是典对应的key值。

        HTML

<span>{{error_msg}}<span>


三、HTML读取字典数据和列表

        字典:使用  .  读取读典key:  dict_name.key

        列表:使用 .索引读取,list_name.0

        views.py

def show(request):    dict_name = {'name':'樱', 'age':19, 'mail':'ying@126.com', 'fav':['football', 'sing', 'cook']}    return render(request,'home.html', dict_name)

        字典HTML:

<p>{{dictname.name}}</p>            \\樱<p>{{dictname.age}}</p>             \\19<p>{{dictname.mail}}</p>            \\ying@126.com

        列表HTML

<p>{{list_name.0}}</p>            \\football<p>{{list_name.1}}</p>            \\sing<p>{{list_name.2}}</p>            \\cook


四、HTML中for循环:

        使用{%%}标记循环语句,并且使用{%endfor%}声明循环结束

          reversed:列表反向迭代

{%for k, v in dict_name%}    \\HTML内容    <p>{{k}}:{{v}}</p>{%endfor%}

//views.pyreturn render(request, 'index.html', {'list_name':['a','b','c']}){%for i in list_name%}    <p>{{i}}</p>        //a,b,c{%endfor%}

    1、empty ,for自带的条件判断,列表为空执行

# list_name = [1,2,3,4]{% for i in  list_name reversed%}        # reversed反向迭代,    <P>{{ list_name.pop }}</P>           # pop是后入先出{% empty %}    <P>null</P>{% endfor %}    # 结果:1234,正常结束,循环结束时列表为空,但是,不会执行empty语句,因为先判断,再使用pop删元素{% for i in list_name %}    <P> has value {{ list_name }}</P>{% empty %}    <P> is null {{ list_name }}</P>{% endfor %}# 结果:is null [],执行empty,因为第一次判断的时候列表就是空的

    2、对多元数组解包:

# dyadic = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]{% for x,y,z,k in dyadic %}    <P>{{ x }}, {{ y }}, {{ z }},{{ k }}</P>{% endfor %}# 结果:1, 2, 3,45, 6, 7,89, 10, 11,12

    3、forloop,获取for循环的统计信息,一般用于列表,因为字典是无序的。

# dyadic = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]# counter,获取列表索引,从1开始{% for i in dyadic %}                    # 结果:1 2 3     {{ forloop.counter }}{% endfor %}# counter0,获取列表索引,从0开始{% for i in dyadic %}                   # 结果:0 1 2    {{ forloop.counter0 }}{% endfor %}# revcounter,获取返向索引,从n开始{% for i in dyadic %}                    # 结果:3 2 1     {{ forloop.revcounter }}{% endfor %}# revcounter,获取返向索引,从n-1开始{% for i in dyadic %}                    # 结果:2 1 0    {{ forloop.revcounter0 }}{% endfor %}# first 当前循环是首个元素为True{% for i in dyadic %}                         # 结果:1 2 3 (1是红色标记)    {% if forloop.first %}        <span >{{ forloop.counter }}</span>    {% else %}        <span >{{ forloop.counter }}</span>    {% endif %}{% endfor %}        # last 当前循环是最后一个元素为True,例如生成链接表时,最后一个不加分割符|{% for i in dyadic %}       # 结果 link | link | link     {% if forloop.last %}        <span >link</span>    {% else %}        <a href="#" >link</a> |    {% endif %}{% endfor %}# parentloop 获取上一级for 循环的信息{% for i in dyadic %}    {% for j in i %}        {% if forloop.parentloop.first %}                # 判断当前i是否是dyadic的第一个元素            <span >{{ j }}</span>      # 如果是,红色标记        {% else %}            <span >{{ j }}</span>        {% endif %}    {% endfor %}    <br>{% endfor %}# 结果:1 2 3 4 (第一行全是红字)5 6 7 8 9 10 11 12



五、HTML中if判断:

{%if 条件1 %}    \\HTML内容    <p>{{k}}:{{v}}</p>{%elif 条件2%}    ...{%else%}    ...{%endfor%}

    1、判断变量是否为空或False:

{% if list_name %}        # list_name是变量名    <P>true</P>{% else %}    <P>false</P>{% endif %}

    2、elif 条件并列

{% with list_name='OK' %}                # 使用with给变量赋值    {% if list_name == 'NO' %}        <P>1</P>    {% elif  list_name == 'OK' %}        # 结果显示OK        <P>OK</P>    {% else %}        <P>others</P>    {% endif %}{% endwith %}

六、HTML模板继承:

    主:{%block tagname%}{%endblock%}

    

    子:声明继承{%extends 'mastr.html'%},只能继承一个母板

    {%block tagname%}内容{%endblock%}

    子继承主的时候,使用block括起来的内容 ,替换主的相应tagname位置。


    include:直接套网页,直接组合,网页的变量也跟随当前网页

    {%include 'tag.html'%}

# c.html{% for i in page_str %}{% include 'hw1/mb.html' %}{% endfor %}# d.html{{ i }}# 结果:d.html里的i直接使用c.html 变量


七、views.py获取html模板传入的数据

    html提交的数据方法有很多种,一般使用两类:POST和GET

        1、POST方法请求:一般用于修改、更新数据。

        2、GET方法请求:以网址显示方式提交,例:http:\\localhost\hw\?id=1&name=david,一般用于向服务器请求数据

        3、其它。put,delete,head,option....

        4、上传文件类型的数据,在Form表单指定-->enctype='multipart/form-data'

     views.py获取数据方法:

        1、POST.get('name','默认值'),获取元素的唯一值,如果没有,赋默认值

        2、POST.getlist('name','默认值'),获取多值元素的列表,如果没有,赋默认值

def get_data(request):    get_post = request.POST.get('user_name')             # 获取HTML元素名为user_name的值 ,<input name='user_name'>    get_post = request.POST.get('user_name',None)        # 找不到user_name元素,返回None    get_list = request.POST.getlist('favor')                       # 获取checkbox,multiple的HTML值    get_get = request.GET.get('user_name')             # 同上    get_get = request.GET.get('user_name',None)        # 同上    get_get = request.GET.getlist('user_name')

        3、FILES.get('name'),获取上传的文件对象,默认显示文件名,
                obj.name显示上传的文件名,
                obj.chunks()迭代器读取数据块,使用for循环读取所有数据,for r in obj.chunks()

def get_file(request):    obj = request.FILES.get('file_obj')    f = open(obj.name, 'wb+')        # 以上传的文件名命名。    for i in obj.chunks():           # 循环读取chunks迭代器数据。        f.write(i)    f.close()

        获取用户请求的数据“

        1、获取文件文件

            file_obj = request.FILES.get()

            file_obj.name

            file_obj.size

            file_obj.chunks()

        2、获取form表单

            request.path_info

            request.POST.getlist()

            request.GET.get()

        3、获取用户环境信息:

            request.environ

            for k,v =request.environ.items():


八、views.py函数返回网址:

    1、render:HTML模板路径,格式:render(request,'HTML模板名',传递的字典)

    2、redirect:返回一个完整的URL(本地或网络地址) ,格式:redirect('http://www.baidu.com')或redirect('/test/') ,

            test前面的/代表根,不加/当前的下级目录 

    3、HttpResponse:返回HTML的字符串,格式:HttpResponse('<p>这只是一个例子</p>')

def show_data(request):    v=1234    # 站内跳转    return render(request,'index.html',{"dict":v})    # 站外跳转    return redirect('http://www.baidu.com')        # 跳转站内根路径,http://ip/blog    return redirect('/blog')        # 跳转站内当前路径下一级,比如当前是http://ip/show,跳转到http://ip/show/blog    return redirect('blog/')        # 直接返回HTML字符串。    return HttpResponse('<p>警告!</p>')



上传文件示例:

urls.py

from django.conf.urls import urlfrom django.contrib import adminimport index.viewsurlpatterns = [    url(r'^admin/', admin.site.urls),    url( r'^mains$',index.views.mains),            # http://ip/mians,跳转到index目录下的views.py下的mains函数    ## url( r'',index.views.mains),                        # http://ip,跳转到index目录下的views.py下的mains函数    url(r'^mains/up$', index.views.rev_file)       # r'^  $'定义^开头$结尾,否则,所有包含此单词的地址都转向,容易混淆]

index.html

    使用了{{}},{%%},模板语言。同时上传

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><form action="up" enctype="multipart/form-data" method="post">   //action,跳转到的网址,action="/up"代表 根目录+up;action="up"代表 当前网址+up              //enctype,form表单可接收文件                 <input type="text" name="user_name" placeholder="Input your name..." />    <input name="up_file" type="file"/>    //type="file",代表可以上传文件型数据    <p>        文件分类:        软件<input type="checkbox" value="技术" name="f_type">        HTML<input type="checkbox" value="HTML" name="f_type">        编程<input type="checkbox" value="编程" name="f_type">    </p>    //创建多选框    <input type="submit" value="提交"></form>{% if f_name %}        //使用if判断是否上传文件,上传文件,显示信息<p><span >{{ u_name }}</span>,Your file:{{ f_name }} Upload Successful!</p>分类:    {% for i in f_type %}            //使用for读取选择的文件分类         {{ i }}    {% endfor %}                    {% else %}                           //未上传文件提示<p><span>You don't upload file!</span></p>{% endif %}</body></html>

test/views.py

from django.shortcuts import renderimport os# Create your views here.def mains(request):    # 首次打开网址,进入的index.html页面    return render(request, 'index.html')def rev_file(request):    # 接收form表单提交的数据    f_name = ''    u_name = ''    f_type = ''    if request.method == 'POST':        f_obj = request.FILES.get('up_file', None)                    # 获取file对象,print(f_obj)是文件名,但实际是对象,因为FILES定义了__repr__或__str__        if f_obj:            #如果有上传的文件            f_name = f_obj.name            u_name = request.POST.get('user_name', None)            f_type = request.POST.getlist('f_type')            #获取checkbox或multiple类型的option选项的数据            f = open(os.path.join('upload', f_name), 'wb+')    #manage.py同级目录的upload文件夹            for i in f_obj.chunks():                           #chunks(),迭代器,使用for读取                f.write(i)            f.close()    return render(request, 'index.html', {'f_name': f_name, 'u_name': u_name, 'f_type': f_type})    # 再返回index.html的内容,但浏览器网址会变,内容也会出现if语句的内容

request其它方法:

  request.GET
  request.POST
  request.method
  request.body     原始数据
  request.path # /upload/
  request.get_full_path() # /upload/?id=1
  request.META     网页原信息
  request.FILES     文件