无法将图像文件嵌入到用户上传的模板中
Unable to embed the image file in the template uploaded by user
我正在尝试在模板中加载上传的图片。图片已正确上传,url 也正确,但我仍然收到 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',)
您收到此错误是因为媒体文件不是自动提供的(默认情况下)。
如果您的 MEDIA_URL
定义为 '/media/'
,那么您可以通过将以下片段添加到您的 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 了解有关为生产服务器执行的操作的更多详细信息。
我正在尝试在模板中加载上传的图片。图片已正确上传,url 也正确,但我仍然收到 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',)
您收到此错误是因为媒体文件不是自动提供的(默认情况下)。
如果您的 MEDIA_URL
定义为 '/media/'
,那么您可以通过将以下片段添加到您的 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 了解有关为生产服务器执行的操作的更多详细信息。