Search code examples
djangodjango-staticfiles

Adding a profile image in django is not working


I am trying to add profile image to my page, but for some reason "my image" text is shown instead of a image.

I do not have any clue about what is wrong in my code, i jave read trough multiple tutorials and they all tells me to do this way. I have a folder "media" in my root directory and inside that i have folder "profile_pics".

I have added these to settings.py

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

these to urls.py

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This is my html

{% load static %}
{%block content%}
    <div class="content-section">
        <div class="media">
            <img src="{% static "profile_pics/default.jpg" %}" alt="My image"/>
            <div class="media-body">
                <h2 class="account-heading">{{ user.username }}</h2>
                <p class="text-secondary">{{ user.email }}</p>
            </div>
        </div>

    </div>
{%endblock content%}

models.py

class profiili(models.Model):
   user=models.OneToOneField(User, on_delete=models.CASCADE)
   kuva=models.ImageField(default='default.jpg', upload_to='profile_pics')


Solution

  • You can try like this if you have successfully uploaded your image throughOnetoOne relation between User and Profiili model

         div class="content-section">
                 <div class="media">
                     <img src="{{user.profiili.kuva.url}}" alt="My i mage"/>
            <div class="media-body">
                <h2 class="account-heading">{{ user.username }} 
                </h2>
                <p class="text-secondary">{{ user.email }}</p>
            </div>
        </div>
    
    </div>