2012-01-29 68 views
0

我有一个上传的看法:验证FileFiled URL在Django

views.py

def upload(request): 

    if request.method == 'POST': 
      form = DocumentForm(request.POST, request.FILES) 
      if form.is_valid(): 
       newdoc = Document(docfile = request.FILES['docfile']) 
       newdoc.save() 

       # Redirect to the document list after POST 
       return HttpResponseRedirect(reverse('wiki.views.upload')) 
     else: 
      form = DocumentForm() # A empty, unbound form 

     # Load documents for the list page 
     documents = Document.objects.all() 

     return render_to_response(
      'wiki/upload.html', 
      {'documents': documents, 'form': form}, 
      context_instance=RequestContext(request) 
     ) 

和我的模板 upload.html

{%extends "base.html"%} 

{%block title%}Upload Documents{%endblock%} 

{%block content%} 
    <!-- List of uploaded documents --> 
    {% if documents %} 
     <ul> 
     {% for document in documents %} 
      <a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a> 
     {% endfor %} 
     </ul> 
    {% else %} 
     <p>No documents.</p> 
    {% endif %} 

    <!-- Upload form. Note enctype attribute! --> 
    <form action="{% url upload %}" method="post" enctype="multipart/form-data"> 
     {% csrf_token %} 
     {{ form.non_field_errors }} 
     {{ form.docfile.help_text }} 
     {{ form.docfile.label_tag }} 
     {{ form.docfile.errors }} 
     {{ form.docfile }} 
     <input type="submit" value="Upload" /> 
    </form> 

{%endblock%} 

我上传一些文件在指定的位置在{MEDIA_ROOT}之下并显示在服务器上,但如果我从该文件夹中删除该文件,该文件名仍显示在网页上。

如何验证并使用我的模板显示上传的文件。

回答

0

在视图或模板标签中,您可以拥有下一个代码。 f是文件

try: 
    exists_file = f.size() 
except IOError: 
    exists_file = False 
+0

@ Goin可以ü请解释通过将代码放在我上面的代码片段..感谢 – sunny 2012-01-30 16:49:55

0

没有从文件系统中的反向链接到Django的 - 如果你上传文件的目录,新的条目将不会被添加到数据库中,同样,如果你删除来自目录的文件,该记录不会从数据库中删除。

如果您从服务器中删除文件,则还需要从数据库中删除该条目。这将使您的文件列表与服务器上实际可用的内容保持同步。

+0

所以你的意思是说,我需要添加一些代码来检查文件是否存在,如果不删除文件后= Document.objects.all()然后返回....如果可能的话,你可以提及代码捕捉。谢谢 – sunny 2012-01-30 14:19:19