locals()用法
生活随笔
收集整理的這篇文章主要介紹了
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()[鍵] = 新值
-------------------------------------------
個性簽名:代碼過萬,鍵盤敲爛!!!
如果覺得這篇文章對你有小小的幫助的話,記得在右下角點個“推薦”哦,博主在此感謝!
總結
以上是生活随笔為你收集整理的locals()用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑视频通话可以录制吗电脑能视频通话吗
- 下一篇: 中国气象站点数据获取的几种方式