我是 Django 的新手,在我的 django HTML 模板/表单上显示图像时遇到问题。实际上,我无法显示它们。我已经按照这个 stackoverflow 问题/链接中所述的解决方案 -如何在 Django 模板中包含图像文件?
但是,当我每次测试时仍然在浏览器上看到损坏的图像。以下是与我的应用程序相关的文件的部分内容(对于查明问题有很大帮助):
--- 设置.py ---
# Media and images used by the templates
MEDIA_ROOT = '/home/acresearch/djangoProjects/fringe/fringe/images'
MEDIA_URL = 'http://localhost:8000/images/'
--- urls.py ---
urlpatterns = patterns('',
(r'^submit/$', submit),
(r'^receipt/$', receipt),
(r'^images/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.MEDIA_ROOT}),
---views.html ---
def submit(request):
if request.method == 'POST':
form = SubmitForm(request.POST, request.FILES)
if form.is_valid():
<omitted code related to handling file upload>
else:
form = SubmitForm()
return render_to_response('submission_form.html', {'form' : form})
--- forms.py ---
class SubmitForm(forms.Form):
email = forms.EmailField(required=True, label='Email address:')
uploadedfile = forms.FileField(required=True, label='File to upload:')
--- submit_form.html ---
<body bgcolor="gray" >
<h1>GRID PE-Classifier Submission Portal</h1>
{% if form.errors %}
<p style="color: red;">Please correct the error{{ form.errors|pluralize }} below. </p>
{% endif %}
<img src="{{ MEDIA_URL }}GRID_LOGO_rev4.jpg" />
<form enctype="multipart/form-data" action="" method="post" >
<div class="field">
<table>
{{ form.email.label }}
{{ form.email }}
</table>
<em>{{ form.email.errors }}</em>
</div>
<div class="field">
<table>
{{ form.uploadedfile.label }}
{{ form.uploadedfile }}
</table>
<em>{{ form.uploadedfile.errors }}</em>
</div>
<input type="submit" value="Submit">
</form>
</body>
最后一件事,我检查了开发服务器的响应,发现应该在我的 HTML 模板/表单上显示为图像的 JPG 已作为 GET 参数传递给 views.py 的提交函数。见下文:
Development server is running at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[24/Apr/2012 04:55:57] "GET /submit/ HTTP/1.1" 200 621
[24/Apr/2012 04:55:57] "GET /submit/GRID_LOGO_rev4.jpg HTTP/1.1" 404 2208
希望你能在这方面帮助我(因为这是我项目的最后一站,我很困惑)。另外,如果你能指出一些全面但直接的关于在 Django 上使用 CSS 和 JS 来美化你的网页的参考,那也很棒。
提前致谢!