我在views.py
有一个视图:
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
print(uploaded_file_url)
context = {
'uploaded_file_url': uploaded_file_url
}
return render(request, 'simple_upload.html', context)
return render(request, 'simple_upload.html')
然后,urls.py
中的url:
urlpatterns = [
path('', views.project_index, name='project_index'),
path('<int:pk>/', views.project_detail, name='project_detail'),
path('upload/', views.simple_upload, name='upload')
]
当我点击路由/projects/upload
时,我得到的不是一个表单,而是一个空页面。然而,simple_upload.html
路由具有以下结构:
{% extends "base.html" %}
<h1>H</h1>
{% load static %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
{% endif %}
<p><a href="{% url 'home' %}">Return to home</a></p>
{% endblock %}
你可以看到,我得到一个空白页。
没有错误发生。
我找到了问题所在。你必须在模板中写{% block page_content %}
而不是{% block content %}
,因为在base.html
中我有这一行:
{% block page_content %}{% endblock %}