我尝试学习如何部署我的 django 项目。 我有一个表单,用户可以在其中上传他的图像。该图像是 Recipe 模型的 ImageField 的内容。 上传过程按预期工作,但是当我尝试在页面上显示这些图片时,它们只是不出现。 这是我的代码:
设置.py:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py(项目一):
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', include('user_auth.urls')),
path('main/', include('main_app.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py:
class Recipe(models.Model):
author = models.ForeignKey(UserExtended, on_delete=models.CASCADE, related_name='recipies')
title = models.CharField(max_length=150, null=False)
category = models.ForeignKey(RecipeCategory, related_name='recipies', on_delete=models.CASCADE, null=True)
image = models.ImageField(upload_to="images/", null=False)
short_description = models.CharField(max_length=250, null=False)
tutorial = models.TextField(null=False, default='')
uploaded_on = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(UserExtended, related_name='liked_recipies')
likes_count = models.SmallIntegerField(default=0)
def __str__(self):
return f'{self.author} {self.title}'
我的模板示例:
<img class="full-recipe-image" src="{{ recipe.image.url }}" alt="Фото блюда">
任何帮助对我来说都是一件幸事,因为我非常绝望。
我尝试更改我的 urls.py 并遇到 MEDIA_ROOT / MEDIA_URL 问题
问题解决了!在我的settings.py中MEDIA_URL应该是真实的互联网URL。