7

Django中views.py和html之间实现字典中键值的传递

 3 years ago
source link: https://blog.51cto.com/u_8669236/5640354
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Django中views.py和html之间实现字典中键值的传递

精选 原创

之前在写Django时,会遇到以下两种情况:1.我在views.py中拿到了一个字典,现在要将字典中的key和value传输到html中进行展示,2.我在html多个输入框中取到的值要转换为字典给views.py进行处理。自己搞定了后做个总结,实际情况中,每个人的html不一样,可能我这种方法不是通用的。

首先看第一种代码,html调用时读取到context中的content(字典格式)后,在html中使用 content.items直接读取

以下为部分views.py的内容
def conf_result(request) :
service = request.POST.get('server').strip()
envnum = int(request.POST.get('env'))
envlook = envlist.objects.get(id="%d" % envnum)
appname = Server.get_by_server(service, envnum)
"""获取disconf配置,这里cfg的输出为字典格式"""
cfg = getdisconf.main(service, envnum)
choice = request.POST
context = {
'envlook' : envlook,
'appoint' : appname,
'content' : cfg,
'navs' : navs.get_all(),
}

if 'getconf' in choice :
return render(request, 'blog/conf_result.html', context=context)
-----------------------------------------------------------------------------
以下为html的部分内容
h5 style="color:blue">服务名称:{{ appoint.appuse }}---{{ appoint.ipuse }}---运行环境:{{ envlook.env_name }}</h5>
{% for k,v in content.items %}
<pre style="color:black">-------------配置文件名称: {{ k }} ----------</pre>
<pre style="color:black">{{ v }}</pre>
{% endfor %}
上述content即对应views.py中的cfg

第二种代码同理,html输入内容后,返回到views中进行处理,views直接使用request.POST.items()处理成字典数据,接下来就可以用字典进行处理数据了。

以下为html的部分内容
<form action="{% url 'result_modify' %}" method="post">
{% csrf_token %}
{% for k,v in content.items %}
<p><B><div name="title{{ forloop.counter }}">{{ k }}</div></B></p>
<P><textarea name="{{ k }}" style="width:800px;height:200px;">{{ v }}</textarea><br>
{% endfor %}
---------------------------------------------------------------------------------------
以下为部分views.py的内容
def result_modify(request) :
choice = request.POST
filedict = {}
"""将html中的key和value转换为字典格式进行处理,用法request.POST.items()"""
for key, value in request.POST.items() :
print(key, value)
filedict[key] = value
  • 打赏
  • 收藏
  • 评论
  • 分享
  • 举报

</div


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK