'Django media file not found
Media file is not getting. The fields related to User model are working(eg. object.username, object.email) but field with ProfileImage is not working.
urls.py
added the below codes.
from django.conf.urls.static import static
from django.conf import settings
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
configured like below.
STATIC_URL = '/static/'
STATICFILES_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
profile_detail.html
these are html code.
{% extends 'base.html' %}
{% block main %}
{{object.email}}
{{request.user}}
<img src="{{object.profileimage.image.url}}">
{% endblock %}
model.py
This model is connected with User model with OneToOne relationship.
def get_profile_upload_to(instance,filename):
new_filename = '{}.{}'.format(uuid4,filename.split('.')[-1])
return "profile/{}/{}".format(instance.user.id, new_filename)
class ProfileImage(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
image = models.ImageField(upload_to=get_profile_upload_to)
uploaded = models.DateTimeField(auto_now_add=True)
views.py
codes related to view.
class ProfileDetailView(DetailView):
model = User
template_name = 'user/profile_detail.html'
Error code at console
Not Found: /media/profile/1/function_uuid4_at_0x7fbf37ce42f0.jpeg
[18/Oct/2019 10:01:45] "GET /media/profile/1/function_uuid4_at_0x7fbf37ce42f0.jpeg HTTP/1.1" 404 3421
Solution 1:[1]
I have added below urlpatterns in apps/urls.py instead of main urls.py thats the reason it is anable to render the image to template.
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Solution 2:[2]
I got the exact same error and doing this worked for me.
Add the following code to urls.py in the project folder:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Note: The changes must be made to the project/urls.py and not app/urls.py
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sanjay |
Solution 2 |