django在循环时仅显示最后一行 [英] django shows only last line while looping
问题描述
我正在尝试将csv文件上传到文件系统并在html中显示,而不存储在数据库中. 下面的代码可以正常工作,但是...
I am trying to upload csv file to filesystem and show within the html without storing in the database. Below code is working but...
我在代码下方添加了一行;
I added below line to my code;
messages.add_message(request, messages.INFO, line)
以便我可以跟随行变量.我可以看到代码正在循环所有csv文件
so that I can follow line variable. I can see that code is looping all the csv file
def check_fp(request):
if not request.user.is_active:
return render(request, 'login.html')
else:
if request.method == 'POST' and request.FILES['csv_file2']:
myfile = request.FILES['csv_file2']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
data = csv.reader(fs.open(filename, mode='r'))
for row in data:
if row[0] != 'FP_Item':
line = row[0]
messages.add_message(request, messages.INFO, line)
context = {'line': line}
return render(request, 'check_fp.html', context)
return render(request, 'check_fp.html', {})
但是我只能看到html文件中csv文件的最后一行.这是我在html文件中的循环.为什么我看不到全部?
But I can only see the last line from the csv file at html file.Here is my loop within html file. Why I am not seeing all ?
<tbody><tr> <td width="25%><a href="#">
{% for line in line %} {{ line }} {% endfor %} </a></td><td>
推荐答案
您的行变量分配和上下文添加不在同一范围内,并且您没有在构建要迭代的列表.您需要将行添加到列表中,并在模板中的行上循环.
Your line variable assignment and context addition are not within the same scope and you're not building a list to iterate through. You'll need to add your lines to a list and loop over those in your template.
您应建立类似于以下内容的行列表:
You should build a list of lines similar to:
def check_fp(request):
if not request.user.is_active:
return render(request, 'login.html')
else:
if request.method == 'POST' and request.FILES['csv_file2']:
myfile = request.FILES['csv_file2']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
data = csv.reader(fs.open(filename, mode='r'))
lines = [] # Added
for row in data:
if row[0] != 'FP_Item':
line = row[0]
lines.append(line) # Added
messages.add_message(request, messages.INFO, line)
context = {'lines': lines} # Modified
return render(request, 'check_fp.html', context)
return render(request, 'check_fp.html', {})
遍历行列表以在模板中构建表时
While looping through the list of lines to build the table in your template:
<tbody>
{% for line in lines %}
<tr>
<td width="25%><a href="#">{{ line }}</a></td>
</tr>
{% endfor %}
</tbody>
这篇关于django在循环时仅显示最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!