NodeReact020
NodeReact020

Reputation: 506

Django - Image not being displayed in the webpage

In my project, I have a DetailView, so a user can view their profile. On here, I want to display their profile picture. However when I open the browser and go to the detail page, no profile picture is displayed. My code is displayed below.

models.py:

class User(AbstractUser):
    profilePic = models.ImageField(upload_to='profile_pics/', default='static/default-profile.png')

views.py:

class DetailProfile(generic.DetailView):
    model = User
    # Template that a users profile picture should be displayed in
    template_name = 'detail_profile.html'

detail_profile.html:

<img width="200px"  src="{{ user.profilePic.url }}" alt="">

Error returned by the browser:

GET http://localhost:8000/media/static/default-profile.png 404 (Not Found)

urls.py (for the users apps):

urlpatterns = [
    path('signup/', views.signup, name='signup'),
    path('login/', views.login, name='login'),
    path('resetone/', views.resetone, name='resetone'),
    path('resetwo/', views.resetwo, name='resetwo'),
    path('viewprofile/<int:pk>', views.DetailProfile.as_view(), name='detail_profile'),
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

SETTINGS.PY:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'proj2/static/')
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

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

Currently, all the users have the file default-profile.png assigned to their profile pic, however later I am going to implement the ability for users to change their profile pic.

default-profile.png is stored in the static folder(Check my settings.py code above), and is also assigned to a user when they first signup. Does anybody know why this file isn't being displayed in the browser and why I am getting returned the error displayed above? Thank you.

Upvotes: 2

Views: 388

Answers (1)

Dev
Dev

Reputation: 197

It seems you have been trying the wrong url. As you are uploading them to profile_pics/ , then all media uploaded resides in the profile_pics directory which should probably be in the root directory. The correct url for the following would be :- http://localhost:8000/media/profile_pics/yourimagename.jpg

Upvotes: 2

Related Questions