zoukankan      html  css  js  c++  java
  • locals()用法

    views.py代码

         def test(request):
        if request.method == 'GET':
            return render(request,'test.html')
        elif request.method == 'POST':
            # print(request.POST)
            username = request.POST.get('username')
            password = request.POST.get('password')
            sex = request.POST.get('sex')
            city = request.POST.get('city')
            print(locals()) #{'city': 'shanghai', 'sex': '1', 'password': '123', 'username': 'root', 'request': <WSGIRequest: POST '/test/'>}
            return render(request,'test.html',locals())
    

    test.html代码

    <form action="/test/" method="post">
        用户名:<input type="text" name="username" value="{{ username }}">
        密码:<input type="password" name="password" >
        <input type="radio" name="sex" value="1" {% if sex in '1' %}checked{% else %}{% endif %}>男
        <input type="radio" name="sex" value="2" {% if sex in '2' %}checked{% else %}{% endif %}>女
        <select name="city" >
            <option value="beijing" {% if city in 'beijing' %}selected{% else %}{% endif %}>北京</option>
            <option value="shanghai" {% if city in 'shanghai' %}selected{% else %}{% endif %}>上海</option>
            <option value="guangdong" {% if city in 'guangdong' %}selected{% else %}{% endif %}>广东</option>
        </select>
        <input type="submit">
    </form>
    

    locals()分析

          locals()方法返回当前局部作用域的变量以字典的形式返回
          {'city': 'shanghai', 'sex': '1', 'password': '123', 'username': 'root', 'request': <WSGIRequest: POST '/test/'>}
          这样就很方便你在后台获取前端发送过来的数据,然后再模板渲染替换字符串。
    
    
          locals()更新字典值,跟普通字典一样
          locals()[键] = 新值
    

    -------------------------------------------

    个性签名:代码过万,键盘敲烂!!!

    如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

  • 相关阅读:
    Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]
    error: RPC failed; result=22, HTTP code = 411
    linux进程控制命令
    主机找不到vmnet1和vmnet8
    sqlserver安装相关问题
    linux下使用libiconv库转码
    Jenkins持续集成
    Ansible性能调优
    Ansible Playbook
    Ansible模块
  • 原文地址:https://www.cnblogs.com/weiweivip666/p/13379014.html
Copyright © 2011-2022 走看看