django shows only last line while looping

2019-09-20 08:00发布

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)

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', {})

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>

标签: django csv line
1条回答
孤傲高冷的网名
2楼-- · 2019-09-20 08:27

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>
查看更多
登录 后发表回答