2011-10-05 67 views
9

我正在嘗試編寫使用Django上傳文件的表單。管理員表單工作得很好,但問題是,當我單擊表單上的提交後,表單會丟失我選擇的文件(文件名消失,'選擇文件'按鈕旁邊出現'沒有選擇文件'),並且視圖將不驗證窗體,因爲文件丟失。我的表單/視圖/文件處理程序看起來就像django example如何使用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 %} 

關於我可能做錯什麼的想法?

+2

你可以發佈模板代碼嗎?需要注意的一點是:「請注意,如果請求方法是POST,並且發佈請求的

具有屬性enctype =」multipart/form-data「,那麼request.FILES將只包含數據。否則,request.FILES將爲空「。 – LaundroMat

+0

作爲一個附註,您可以使用'auto_now'和'auto_add_now'([鏈接到文檔](https://docs.djangoproject.com/en/1.3/ref/models/fields/#datefield))屬性DateTimeFields,以便您不需要覆蓋保存方法。 'auto_now'每次保存更新日期,'auto_add_now'只是創建日期, –

+2

將** enctype =「multipart/form-data」**添加到表單標記可以解決這個問題,但現在它拋出一個MultiValueDictKeyError,其中描述爲「在]}>中找不到密鑰'file' – jdickson

回答

7

改變了...

handle_uploaded_file(request.FILES['file']) 

要這個......

handle_uploaded_file(request.FILES['attachment']) 

的文件存儲在您的字段的名稱POST數據。