9
我正在嘗試編寫使用Django上傳文件的表單。管理員表單工作得很好,但問題是,當我單擊表單上的提交後,表單會丟失我選擇的文件(文件名消失,'選擇文件'按鈕旁邊出現'沒有選擇文件'),並且視圖將不驗證窗體,因爲文件丟失。我的表單/視圖/文件處理程序看起來就像django example。如何使用Django上傳文件
forms.pyclass 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 %}
關於我可能做錯什麼的想法?
你可以發佈模板代碼嗎?需要注意的一點是:「請注意,如果請求方法是POST,並且發佈請求的
作爲一個附註,您可以使用'auto_now'和'auto_add_now'([鏈接到文檔](https://docs.djangoproject.com/en/1.3/ref/models/fields/#datefield))屬性DateTimeFields,以便您不需要覆蓋保存方法。 'auto_now'每次保存更新日期,'auto_add_now'只是創建日期, –
將** enctype =「multipart/form-data」**添加到表單標記可以解決這個問題,但現在它拋出一個MultiValueDictKeyError,其中描述爲「在]}>中找不到密鑰'file' –
jdickson