在django-templates / django-forms上显示图像/背景图像

时间:2012-04-24 10:01:13

标签: python django templates django-forms

我是Django的新手,我在django HTML模板/表单上显示图像时遇到问题。实际上,我无法显示它们。我已经按照此stackoverflow问题/链接 - How do I include image files in Django templates?

上的说明进行了操作

但是,每当我测试它时,我的浏览器上仍然会出现损坏的图像。 以下是与我的应用程序相关的文件的部分内容(这可以帮助找出错误的内容):

--- settings.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:')

--- submission_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的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来美化你的网页的点参考,那也会很棒。

提前致谢!

1 个答案:

答案 0 :(得分:0)

您尚未使用RequestContext呈现模板,因此MEDIA_URL未被传递。