代码之家  ›  专栏  ›  技术社区  ›  furang

Django,动态设置img src

  •  1
  • furang  · 技术社区  · 8 年前

    在有人将其标记为重复之前,我已经阅读并尝试了以下线程中的解决方案:

    Use Django Template Tags in img src

    django 1.5 - How to use variables inside static tag

    Django: Insert image in a template whose path is dynamic

    但仍然无法使其发挥作用。 所以我使用Django内置的UpdateView来更新数据库条目,并尝试将图像加载到模板中,其中 src 动态如下:

    编辑\u journal\u entry\u表单。html

    {% extends 'base.html' %}
    {% load staticfiles%}
    <form method="post">
        {% csrf_token %}
        {% static "" as baseUrl %}
        <img src="{{ baseUrl }}/lpr_images/{{journalEntry.license_plate_nr_img}}"></img>
        <img src="{% static "" %}/lpr_images/{{journalEntry.license_plate_nr_img}}" />
        <img id="edit_img" src="{% static 'lpr_images/' %}{{journalEntry.license_plate_nr_img}}" alt="Image not read!"/>
        {{ form.as_p }}
        <button class="btn btn-success" type="submit">Submit</button>
    ...
    

    视图。py公司

    class JournalEntryUpdate(UpdateView):
        model = JournalEntry
        template_name = 'gate_operator/edit_journal_entry_form.html'
        success_url = '/gate_operator/journal/'
        fields = [
            'license_plate_nr',
            'license_plate_nr_img',
            ...
        ]
    
        def form_valid(self, form):
            object = form.save(commit=False)
            object.user = self.request.user
            object.save()
            return super(JournalEntryUpdate, self).form_valid(form)
    

    型号。py公司

    class JournalEntry(models.Model):
        license_plate_nr = models.CharField(max_length=20, blank=True)
        license_plate_nr_img = models.CharField(max_length=100, blank=True)
        ...
    

    所有这些在控制台中都不起作用,我只能看到静态部分: GET http://127.0.0.1:8000/static//lpr_images/ 404 (Not Found) 我尝试对url进行硬编码,以确保路径正确,因此这成功显示了图像: http://127.0.0.1:8000/static//lpr_images/2018_04_26_08_43_25.png 那么,我在这里遗漏了什么或做错了什么?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alasdair    8 年前

    在模板中,应使用 journalentry (全部小写),而不是 journalEntry 。