【发布时间】:2017-05-19 12:36:18
【问题描述】:
我的 django 项目中只有一个上传文件表单(我使用的是 1.10)。实际上一切都很好,但是由于人们会将 csv 文件上传到服务器,我需要将我的逻辑限制为仅请求具有特定名称和格式的文件。
这是我的代码:
views.py
def list(request):
# Handle file upload
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('action'))
else:
messages.add_message(request, messages.ERROR,
'Something went wrong with files! Please contact the system administrator')
return render(request, 'upaction-report.html')
# Load documents for the list page
# Render list page with the documents and the form
return render(request, 'upaction-report.html', {'form': form})
forms.py
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='File format should be under the following format:',
help_text='- .csv format and under the name "Action_Report"',
)
模板 html
<form action="{% url "list" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }}</p>
<p> {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload File"/></p>
</form>
猜猜如何应用该限制?如果文件不正确,只需弹出一条消息,告诉重试,直到它具有正确的格式和名称。感谢您的宝贵时间,如果您需要更多详细信息,请告诉我。
【问题讨论】:
标签: python html django if-statement file-upload