为什么这个django-python片段还会在上传的文档列表中显示已删除的文件?
views.py
def lists(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
filename = Document(docfile = request.FILES['docfile'])
filename.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('sdm:lists'))
# return render_to_response(reverse('sdm:lists'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'sdm/lists.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
lists.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
{% for document in documents %}
<li><a href="{{document.docfile.url }}">{{ document.docfile.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url sdm:lists %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{form.non_field_errors }}</p>
<p>{{form.docfile.label_tag }} {{form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" name="press" value="Upload" /></p>
</form>
</body>
浏览器输出
f14 is latest uploaded file and rest all files have been deleted from respective folders but why is that it is still showing all files in list when are not even present?
我是django-python的新手,但我试图调试它,但发现了这个。
>>> from sdm.models import Document
>>> Document.objects.all()
[<Document: Document object>, <Document: Document object>, <Document: Document
object>,<Document: Document object>, <Document: Document object>, <Document: Document
object>,<Document: Document object>, <Document: Document object>, <Document: Document
object>,<Document: Document object>, <Document: Document object>, <Document: Document
object>,<Document: Document object>, <Document: Document object>, <Document: Document
object>]
不知道如何看实际对象??
由于
修改: 正如答案和评论中所指出的,我想告诉你我正在直接删除上传文件夹中的文件。有什么办法可以强制ORM对象在文件夹
中没有文件时自动更新答案 0 :(得分:1)
我看不到你如何删除Document
。您应该有如下方法。
def delete(request):
if request.method != 'POST':
raise HTTP404 # don't forget to import
else:
docId = request.POST.get('doc-id', None)
if docId is not None:
docToDel = Document.objects.get(pk=docId)
# delete the file using docToDel.docfile
docToDel.delete()
return HttpResponse('Whatever message you want.')
更新1
如果要在直接删除文件时自动删除对象,可以迭代Document对象并检查文件是否存在。但是您需要在列出之前或定期运行此过程。