Django--其他常用功能之保留原页面所有内容

博客核心内容:


1、Django–其他常用功能之保留原页面所有内容
2、简单版本


如何带着参数过去
如何将参数带回


代码示例:
部分1:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # 我们工作中所说的Api其实指的就是url链接路由:http://127.0.0.1:8000/asset.html
    # 对于api我们既可以发送post请求,也可以发送get请求.
    url(r'^asset.html$', views.asset),
    url(r'^host_list.html$', views.host_list),
    url(r'^add_host.html$', views.add_host),
]

部分2:

from django.shortcuts import render,HttpResponse,redirect
from django.views.decorators.csrf import csrf_exempt,csrf_protect
# Create your views here.


#通过装饰器避免了csrf_token攻击
@csrf_exempt
def asset(request):
    """
    我们通常情况下提交数据一般有两种方式:Ajax和Form表单的方式
    """
    if request.method == 'GET':
        return HttpResponse('GET 收到...')
    else:
        print(request.POST)
        # print(request.body)
        """
        <QueryDict: {'salary': ['2000'], 
                     'username': ['Angela'], 
                     'password': ['123456']}
        >
        <QueryDict: {'name': ['zhangming'], 
                     'page': ['10']}
        >
        注意:如果request.post里面没有值,我们就到request.body里面去拿
        b'{"password": "123456", "username": "Angela", "salary": 2000}'
        """
        return HttpResponse('POST 收到...')


from django.http.request import QueryDict

def host_list(request):
    print(request.GET,type(request.GET))
    """
    <class 'django.http.request.QueryDict'>
    """
    print(request.GET.urlencode())
    """
    <QueryDict: {'page': ['10'], 'name': ['zhangming']}>
    page=10&name=zhangming
    通过request.GET.urlencode()可以将具体参数值的信息获取到
    但是我们一般不用现成的,而是重新赋予一个变量
    This QueryDict instance is immutable:默认QueryDict()对象是不可以被修改的
    """
    obj = QueryDict(mutable=True)
    obj['_canshu'] = request.GET.urlencode()
    print(obj['_canshu'])
    url_params = obj.urlencode()
    print(url_params)  #_canshu=name%3Dzhangming%26page%3D10
    """
    page=10&name=zhangming
    url_params=page%3D10%26name%3Dzhangming
    %3D为=   %26为&
    此时params将作为一个变量等于后面的值
    """
    hosts = ['c1.com','c2.com','c3.com']
    return render(request,'host_list.html',{'hosts':hosts,'url_params':url_params})


def add_host(request):
    """
    接下来我们就要想着如何返回原来的页面
    """
    print(request.GET)
    """
    <QueryDict: {'_canshu': ['name=zhangming&page=10']}>
    """
    if request.method == 'GET':
        return render(request,'add_host.html')
    else:
        print('------')
        print(request.POST)
        """
        <QueryDict: {'csrfmiddlewaretoken': ['FmhpzJaCnoJhn2pxzAG70fBsescpBmFenNjS3Vtofm3hvXhfXXDnujIF25j7xuSg'], 'hostname': ['']}>
        """
        url_params = request.GET.get('_canshu')
        print('参数是》》》》')
        print(url_params)
        hostname = request.POST.get('hostname')
        print(hostname)
        url = "/host_list.html?"+url_params
        return redirect(url)

部分3:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
     {# 注意:这里不能写action,这样的话才话向当前的url进行提交 #}
     <form method="POST">
         {% csrf_token %}
         <input type="text" name="hostname">
         <input type="submit" value="提交">
     </form>
</body>
</html>

部分4:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {# a标签默认就是get请求 #}
    {# GET http://127.0.0.1:8000/add_host.html   #}
    {# 这样我们发送数据的时候就会带着参数去发送相应的数据 #}
    <a href="/add_host.html?{{ url_params }}">添加</a>
    <ul>
        {% for item in hosts %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
</body>
</html>

效果展示:
这里写图片描述

简单版本

切记:Form表单出不要写action,这样才会向页面的当前链接进行提交.
通过url_params = request.GET.get(‘_canshu’)可以获取get中的参数值


代码示例:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^host_list.html$', views.host_list),
    url(r'^add_host.html$', views.add_host),
]
from django.shortcuts import render,HttpResponse,redirect
from django.http.request  import  QueryDict


def host_list(request):
    obj = QueryDict(mutable=True)
    obj['_canshu'] = request.GET.urlencode()
    url_params = obj.urlencode()
    print(url_params)
    """
    _canshu=name%3Dzhangming%26page%3D10
    """
    hosts = ['host1','host2','host3']
    return render(request,'host_list.html',{'hosts':hosts,'url_params':url_params})

def add_host(request):
    if request.method == "GET":
        return render(request,'add_host.html')
    else:
        url_params = request.GET.get('_canshu')
        print(url_params)
        url = '/host_list.html?'+url_params
        return redirect(url)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        <input type="text" name="hostname">
        <input type="submit" value="提交">
    </form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a href="/add_host.html?{{ url_params }}">添加主机</a>
    <ul>
        {% for host in hosts %}
            <li>host</li>
        {% endfor %}
    </ul>
</body>
</html>
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a2011480169/article/details/78160090
文章标签: django url
个人分类: Python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Django--其他常用功能之保留原页面所有内容

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭