Search code examples
djangoimagemodelsdisplay

Django not displaying image from model


I cannot get the image to show up in my HTML template. Right now it just displays a broken image.

urls.py

from django.conf.urls import url, include
from django.contrib import admin
from home import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^$', views.index),
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('accounts.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    description = models.CharField(max_length=100, default='')
    city = models.CharField(max_length=100, default='')
    website = models.URLField(default='')
    phone = models.IntegerField(default=0)
    profile_picture = models.ImageField(upload_to='profile_pics', blank=True)

profile.html

<div class="container">
  <br>
  <h2>{{ user }}</h2>
  <br>

  <p>Name: {{ user.first_name }} {{ user.last_name }}</p>
  <img src="{{ user.userprofile.profile_picture.url }}">
  <p></p>
  <p>About Me: {{ user.userprofile.description }}</p>
  <p>Phone Number: {{ user.userprofile.phone }}</p>


  <a href="{% url 'edit_profile' %}">Edit Profile</a><br>


<!-- if profile is updated succesfully -->
 {% if messages %}
 {% for message in messages %}

 <br><br>{{ message }}

 {% endfor %}
 {% endif %}

</div>

Output:

Profile

I'm not sure what I'm doing wrong here. I believe that I have the medial_url/media_root set up correctly, and I can see the correct path in my directory with the image inside of it. Any help is greatly appreciated.


Solution

  • You should also add the following to urls.py,

    urlpatterns = [
        url(r'^$', views.index),
        url(r'^admin/', admin.site.urls),
        url(r'^accounts/', include('accounts.urls')),
    ] 
    
    if settings.DEBUG == True:
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)