我正在尝试开发一个能够使用CRUD文件的Django应用程序。 目前我已经开发了上传下载功能,但是当我想要删除项目时,事情变得非常困难。
* Views.py *
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
all_docs = Document.objects.all()
repeated = False
if form.is_valid():
for doc in all_docs:
if Document(docfile=request.FILES['docfile']).docfile == doc.docfile:
repeated = True
if not repeated:
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('list'))
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(
request,
'list.html',
{'documents': documents, 'form': form}
)
* Forms.py *
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file'
)
* List.html *
<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 "list" %}" 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" value="Upload"/></p>
</form>
</body>
*输出*
正如您所看到的,当我上传文档时,它会存储在数据库中,但我不知道如何制作按钮以便能够选择项目并将其删除,就像我做的那样上传系统。
Document的模型有一个属性ID和一个FileField。
我知道这是一个非常具体和密集的问题,但我花了太多时间研究它并且我没有得到结果。我开始开发这段代码以使视图能够删除该项目,但我不知道如何选择它:
*删除查看*
def remove_document(request):
if request.method == 'POST':
form = DocumentForm()
# Dont know how to reference the item I want to delete
document = request.POST.objects.get(docfile = ?????)
db_documents = Document.objects.all()
for db_doc in db_documents:
if db_doc = document:
document.delete()
return render(
request,
'list.html',
{'documents': documents, 'form': form}
)
我是Django的新手,它的架构模型对我来说非常棘手
谢谢!