So my image is not displaying, here is my code: models.py:
from django.contrib.auth.models import User
from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _
class ProfileImage(models.Model):
"""
Profile model
"""
user = models.OneToOneField(
verbose_name=_('User'),
to=settings.AUTH_USER_MODEL,
related_name='profile',
on_delete=models.CASCADE
)
avatar = models.ImageField(upload_to='profile_image')
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mifamiliaesundesastre/media')
urls.py:
from django.contrib import admin
from django.urls import path, include
from Home.views import home_view
from accounts.views import login_view, register_view, logout_view, user_home
from chat.views import Messages
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name='home'),
path('login/', login_view),
path('signup/', register_view),
path('logout/', logout_view),
path('home/', user_home),
path('messages/', include('chat.urls')),
path('messages/', Messages),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
user_home.html:
<img src="{{ user.profileimage.avatar.url }}" alt="profile image">
I did all correct, also I can see my images in my media folders but in my template does not show up, does anybody know what is wrong with my code?
Sinc the related_name='profile'
in the ForeignKey
is 'profile'
, you access it with
<img src="{{ user.profile.avatar.url }}" alt="profile image">
The related_name=…
parameter [Django-doc] is the name of the relation in reverse. So to obtain the related ProfileImage
object from a User
object.
You can also decide to change related_name=…
to related_name='profileimage'
, then you of course use {{ user.profileimage.avatar.url }}
.