【问题标题】:Unable to embed the image file in the template uploaded by user无法在用户上传的模板中嵌入图像文件
【发布时间】:2019-10-12 04:56:33
【问题描述】:

我正在尝试在模板中加载上传的图片。图片已正确上传,网址也正确,但我仍然收到 404 错误。错误是:- GET http://127.0.0.1:8000/media/complaints_image/motivational-inspirational-quotes-30.jpg 404(未找到)

图像存在于文件夹中:- inside the media folder image is present

模板

{% if complaint.media %}
 <img src="{{ complaint.media.url }}" height="100px" width="100px" >
{% endif %}

settings.py

MEDIA_DIR  = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'

models.py

class Complaints(models.Model):
  media = models.ImageField(upload_to='complaints_image',blank=True)

forms.py

class ComplaintForm(forms.ModelForm):

class Meta():
    model = Complaint
    fields = ('department','heading','text','media',)

【问题讨论】:

    标签: django django-templates django-media


    【解决方案1】:

    您收到此错误是因为没有自动提供媒体文件(默认情况下)。


    如果您的MEDIA_URL 被定义为'/media/',那么您可以通过将以下sn-p 添加到您的entry-level urls.py 来提供您的媒体文件:

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
    
    

    阅读Serving files uploaded by a user during development了解更多详情。


    注意:这种提供媒体(和静态)文件的方式不适合生产使用!

    阅读this article 了解有关生产服务器的更多详细信息。

    【讨论】:

    • 谢谢,已解决
    猜你喜欢
    • 1970-01-01
    • 2013-10-31
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-02
    • 2022-10-24
    • 2016-12-05
    • 1970-01-01
    相关资源
    最近更新 更多