简体   繁体   中英

Django media files not loading

I have a users app, profile is a model created in its models.py .The image is present in /media/profile_pics/ but even after giving the full path in src it is not loading. I cannot figure out why.Adding the relevant files below.

models.py

from django.contrib.auth.models import User

from django.db import models
from django.contrib.auth.models import AbstractUser


class profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='media/default.jpg', upload_to='profile_pics')


def __str__(self):
    return f'{self.user.username} Profile'

profile.html

<!DOCTYPE html>

{% extends 'base2.html' %}
{% load crispy_forms_tags %}
{% load static %}


<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>profile</title>
</head>
{% block content %}
<body style="margin-left: 300px">
<div class="content-section">
    <div class="media">
        <img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
        <img class="rounded-circle account-img" src="E:\py-projects\hello-world\media\profile_pics\profile1.png">

    </div>
</div>

</body>
{% endblock %}

</html>

settings.py

STATIC_URL = '/static/'

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

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),

]

urls.py (the main urls.py, not of app users )

from django.contrib import admin
from django.urls import path, include
from users.views import profile
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('users.urls'), name='index'),
    path('profile/', profile, name='profile'),

]

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

i feel stupid for not seeing this :| had to add this.

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

Use this in your urls.py

from django.conf.urls import url
from django.conf import settings
from django.views.static import serve


urlpatterns = [
    url(r'^media/(?P<path>.*)$', serve, {'document_root': 
        settings.MEDIA_ROOT}),
    url(r'^static/(?P<path>.*)$', serve, {'document_root': 
        settings.STATIC_ROOT}),
]

And in your settings.py

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM