繁体   English   中英

如何使用Django上传文件

[英]How to upload a file with Django

我正在尝试使用Django编写表单来上传文件。 管理表单工作正常,但问题是,在我单击表单上的提交后,表单丢失了我选择的文件(文件名消失,'选择文件'按钮旁边出现'没有文件选择'),视图不会验证表单,因为文件丢失。 我的表单/视图/文件处理程序看起来就像django示例

forms.py

class AttachForm(forms.ModelForm):
    class Meta:
            model = Attachment
            exclude = ('insp', 'contributor', 'date')

views.py

def handle_uploaded_file(f):
    destination = open('some/file/name.txt', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

def attach(request, insp_id):
    if request.method == 'POST':
            form = AttachForm(request.POST, request.FILES)
            if form.is_valid():
                    handle_uploaded_file(request.FILES['file'])
                    f = form.save(commit=False)
                    f.contributor = request.user
                    f.insp = insp_id
                    f.save()
                    return HttpResponseRedirect(server + '/inspections/' + str(insp_id) + '/')
    else:
            form = AttachForm()
    return render_to_response('attach.html', locals(), context_instance=RequestContext(request))

models.py

class Attachment(models.Model):
    insp = models.ForeignKey(Inspection)
    contributor = models.ForeignKey(User, related_name='+')
    date = models.DateTimeField()
    title = models.CharField(max_length=50)
    attachment = models.FileField(upload_to='attachments')
    def __unicode__(self):
        return self.title
    def save(self):
        if self.date == None:
            self.date = datetime.now()
        super(Attachment, self).save()
    class Meta:
        ordering = ['-date']

attach.html

{% extends "base.html" %}

{% block title %}Add Attachment{% endblock %}

{% block content %}
<h2>Attach File: Inspection {{ insp_id }}</h2>
<p>This form is used to attach a file to an inspection.</p>
<form action="." method="POST" autocomplete="off">{% csrf_token %}
    <table cellspacing="10" cellpadding="1">
        {% for field in form %}
            <tr>
            <th align="left">               
                {{ field.label_tag }}:
            </th>
            <td>
                {{ field }}
            </td>
            <td>
                {{ field.errors|striptags }}
            </td>
        </tr>
        {% endfor %}
        <tr><td></td><td><input type="submit" value="Submit"></td></tr>
    </table>
</form>
{% endblock %}

我可能做错什么的想法?

改变这个......

handle_uploaded_file(request.FILES['file'])

对此......

handle_uploaded_file(request.FILES['attachment'])

该文件存储在POST数据中,并带有您的字段名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM