在 Django 模板中渲染并行数组

在 Django 模板中渲染并行数组通常涉及使用模板语言中的循环结构来遍历和展示数组中的每个元素。假设你有一个名为 items 的数组,你可以按照以下方式在 Django 模板中渲染它:

复制代码
<ul>
  {% for item in items %}
    <li>{{ item }}</li>
  {% endfor %}
</ul>

在这个例子中,items 是一个 Python 列表,它会在模板中被展开并显示每个元素。每次迭代循环时,变量 item 将代表数组中的一个元素,并通过 {``{ item }} 的方式插入到 HTML 中。

如果 items 是一个包含字典或对象的列表,你可以使用点表示法访问它们的属性。例如,如果 items 是一个包含对象的列表,每个对象有一个 name 属性,可以这样访问:

复制代码
<ul>
  {% for item in items %}
    <li>{{ item.name }}</li>
  {% endfor %}
</ul>

这种方法使得在 Django 模板中展示和渲染多个数组元素非常方便和灵活。

1、问题背景

在使用 Django 渲染模板时,有时需要同时渲染两个数组的数据,一个数组是需要输出的数据,另一个数组是用于删除项的表单集。由于 Django 不支持在模板标签中使用布尔运算符,直接将这两个数组打包在一起可能会导致只渲染第一个项目和第一个表单。因此,需要一种方法将这些项目打包在一起,以便在同一个 for 循环中渲染它们。

2、解决方案

可以使用 Python 内置的 zip 函数来解决这个问题。zip 函数可以将多个可迭代对象打包成一个元组的列表,其中每个元组包含这些可迭代对象中相应位置的元素。

在视图中,可以使用以下代码将 post 数组和 delpostformset.forms 数组打包在一起:

python 复制代码
post_and_form = zip(post, delpostformset.forms)

然后在模板中,可以使用以下代码来渲染打包后的数组:

html 复制代码
{% for post, form in post_and_form %}
{% endfor %}

这样,就可以在一个 for 循环中渲染这两个数组的数据了。

以下是一个完整的示例代码:

视图

python 复制代码
from django.shortcuts import render_to_response
from django.template import RequestContext
from forum.models import forum, UserProfile
from django.contrib.auth.decorators import login_required
from forum.forms import PostForm, PostDeleteForm, ReadForumForm
from django.forms.models import modelformset_factory

@login_required
def forums(request ):

    post = list(forum.objects.filter(child='0') & forum.objects.filter(deleted='0'))
    user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
    newpostform = PostForm(request.POST)
    deletepostform = PostDeleteForm(request.POST)
    DelPostFormSet = modelformset_factory(forum, exclude=('child','postSubject','postBody','postPoster','postDate','childParentId'))
    readform = ReadForumForm(request.POST)
    if newpostform.is_valid():
        topic = request.POST['postSubject']
        poster = request.POST['postPoster']
        newpostform.save()
    newpostform = PostForm(initial = {'postPoster':user.id})
    post = list(forum.objects.filter(child='0') & forum.objects.filter(deleted='0'))

    else:
        newpostform = PostForm(initial = {'postPoster':user.id})

    if request.method == 'POST':
        delpostformset = DelPostFormSet(request.POST)
        if delpostformset.is_valid():
            delpostformset.save()

    else:
        delpostformset = DelPostFormSet(queryset=forum.objects.filter(child='0', deleted='0'))

    post_and_form = zip(post, delpostformset.forms)

    return render_to_response('forum.html', {'post': post_and_form, 'newpostform': newpostform, },  context_instance=RequestContext(request))

模板

html 复制代码
<table class="results">
<tr class="inner_results_header"><td >Title</td><td>Date/Time</td><td>Poster</td>      <td>Body</td><td><form method="post" id="form" action=""  class="usertabs accfrm"><input type="submit" value="Delete" /></td></tr>  
{{formset.management_form}}
{% for post, form in post   %}



{% url forum_view p.postID  as post_url%} 
<tr  class="inner_results {% if forloop.counter|divisibleby:2 %}evens{% else %}odds{% endif %}"><span onclick="document.location.href='{{post_url}}';"><td>{{ p.postSubject}}</td><td>{{p.postDate}}</td><td>{{ p.postPoster}}</td><td>{{ p.postBody|truncatewords:50}}</td></span><td>


{{ form.as_p }}


</td></tr> 

{% endfor %}

<tr class="inner_results_header"><td >Title</td><td>Date/Time</td><td>Poster</td> <td>Body</td><td><input type="submit" value="Delete" /></form></td></tr>  

这样,就可以在 Django 模板中渲染并行数组了。

相关推荐
史迪奇_xxx8 分钟前
10、一个简易 vector:C++ 模板与 STL
java·开发语言·c++
2301_8012522211 分钟前
Java中的反射
java·开发语言
Kiri霧33 分钟前
Rust开发环境搭建
开发语言·后端·rust
小池先生35 分钟前
服务请求出现偶发超时问题,经查服务本身没问题,问题出现在nginx转发。
运维·服务器·nginx
weixin-a1530030831637 分钟前
[数据抓取-1]beautifulsoup
开发语言·python·beautifulsoup
阿里云大数据AI技术1 小时前
云栖实录|MaxCompute全新升级:AI时代的原生数据仓库
大数据·数据库·云原生
asdfg12589631 小时前
如何判断一个地址是否可以用作主机 IP 地址?
服务器·网络·tcp/ip
小杨同学yx1 小时前
有关maven的一些知识点
java·开发语言
不剪发的Tony老师2 小时前
Valentina Studio:一款跨平台的数据库管理工具
数据库·sql
重生之我要当java大帝2 小时前
java微服务-尚医通-编写医院设置接口下
java·开发语言·sql