【发布时间】:2019-09-19 15:14:16
【问题描述】:
我有一个 html 表单,用户可以上传文件,但是如果用户直接点击提交按钮而不上传任何文件,django 会出错。我该如何控制这个问题?
上传.html
<!-- Upload form. Note enctype attribute! -->
<form method="post" enctype="multipart/form-data" multiple>
{% csrf_token %}
<input type= "file" name ="docfile" multiple/>
<button id="yukle" type="submit" value="Upload">
<img src="/static/img/upload.png" width=28 height=30 alt="Yükle"/>
</button>
</form>
views.py
def SenetList(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
dosya_tipi = "Senet"
context = upload(request.FILES.getlist('docfile'),form, dosya_tipi)
return render(request, 'operations/upload.html', context)
else:
form = DocumentForm()
return render(request, 'operations/upload.html', {'form': form})
forms.py
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)
我给出了这样的错误:
/upload/senet 处的值错误
视图 operations.views.SenetList 未返回 HttpResponse 对象。它返回 None 。
【问题讨论】:
-
这个模板是渲染前还是渲染后?
-
我不能完全理解你的问题。你能解释一下吗? @Moha369
-
渲染前:
{{ form }},渲染后:{{<form method = "POST"> ... </form>}} -
在渲染之前我会说,看看 csrf 的东西
-
如果您在 HTML 中创建表单,那么为什么要在
forms.py中创建表单?或者如果你有一个 python 表单,为什么要创建 html?