0

我有一个带有文件上传字段的表单,该字段将显示在模板中

提交表单后,如果发现错误并返回页面,上传文件将消失,谁能帮我了解如何在发现错误后在表单页面中显示上传文件

以下是表格:

class Project_f(forms.Form):
    info=forms.CharField(required=True)
    file=forms.FileField(required=False)

和模板:

<form action="" method="post" id="form1" enctype="multipart/form-data" ....>
{% csrf_token %}

            <td ><label for="id_info">product info:</label></td>
            <td colspan=3 >{{form.info}}</td>   
            <td >&nbsp;</td>
        </tr>
        <tr class="tr_blank"></tr>
        <tr>
            <td >&nbsp;</td>
            <td><label for="id_attachement_id">add attachment:</label></td>
            {% if attachments %}
                {% for attachment in attachments %}
                <td colspan="2">
                current attachment:&lt;div class='attachmentdd'id={{attachment.id}}><a href={{attachment.file}}>{{attachment.file}}</a>
                <br>modify:&lt;input id="txt" class="input_text" type="file" name="attachement_id" style="width:100%;height:23px;">
                </div>
                {% endfor %}
            {% else %}
            <td >{{form.attachement_id}}</td>   
            {% endif %}
            <td >&nbsp;</td>
        </tr></form>

以下是views.py

Pr_form=Project_f(request.POST,request.FILES)
if Pr_form.is_valid():
      ......
else:
       c={'form': Pr_form,'user':login_name,'ourteam':ourteam}
       c.update(csrf(request))
       return  render_to_response('project_form.html',c,context_instance=RequestContext(request))

提交表单后,如果服务器发现错误,显示错误信息时不会显示上传文件路径

4

1 回答 1

0

您可以通过视图中的 request.FILES 字典访问上传的文件来获取信息,然后将这些变量传递给您的模板。

[更新]

好的,所以根据您视图中的更新代码,这里有一个示例,说明如何从 request.FILES 集合中获取信息,以及如何稍微清理代码:

#views.py
from django.shortcuts import render #assumes Django 1.3+

from your_app.forms import Project_f


def my_view(request):
    #always lower-case variable names, as classes are always capitalized
    pr_form = Project_f(request.POST or None, request.FILES or None)

    if request.method == 'POST':
        if pr_form.is_valid():
           my_file = request.FILES.get('my_file')
           file_name = my_file.name
           # do something with file_name, etc.

           pr_form.save()
    return render(request, 'project_form.html', {'form' : pr_form,
        'user' : login_name, 'ourteam' : ourteam})
于 2012-04-23T13:09:59.277 回答