Не удается добиться отображения изображений профиля с помощью django
Я работаю над базовым учебником по загрузке изображений в django и застрял. Я пытаюсь позволить пользователю загрузить файл, сохранить его в папке, а затем сохранить адрес этого изображения в базе данных. Эта часть вроде бы работает. Затем я пытаюсь создать простую страницу для отображения всех изображений, чтобы убедиться, что она работает, и тег img в HTML продолжает иметь src "неизвестно". Я не уверен, в чем именно проблема, потому что нигде не возникает никаких ошибок.
Views.py
from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic.edit import CreateView
from django.views.generic import ListView
from .models import UserProfile
# Create your views here.
class CreateProfileView(CreateView):
template_name = "profiles/create_profile.html"
model = UserProfile
fields = "__all__"
success_url = "/profiles"
class ProfilesView(ListView):
model = UserProfile
template_name = "profiles/user-profiles.html"
context_object_name = "profiles"
Models.py
from django.db import models
# Create your models here.
class UserProfile(models.Model):
image = models.ImageField(upload_to="image")
User-Profiles.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Profiles</title>
</head>
<body>
<ul>
{% for profile in profiles %}
<li>
<img src="{{ profile.url }}">
</li>
{% endfor %}
</ul>
</body>
</html>
Forms.py
from django import forms
class ProfileForm(forms.Form):
user_image = forms.ImageField()
Urls.py в /profiles
from django.urls import path
from . import views
urlpatterns = [
path("", views.CreateProfileView.as_view()),
path("list", views.ProfilesView.as_view())
]
Urls.py в папке проекта
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("reviews.urls")),
path("profiles/", include("profiles.urls"))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Settings.py
Вы используете .url
поля .image
так:
{% for profile in profiles %}
<li>
<img src="{{ profile.image.url }}">
</li>
{% endfor %}