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()[键] = 新值


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM