Reputation: 53
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.
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)
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')
these are html code.
{% extends 'base.html' %}
{% block main %}
{{object.email}}
{{request.user}}
<img src="{{object.profileimage.image.url}}">
{% endblock %}
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)
codes related to view.
class ProfileDetailView(DetailView):
model = User
template_name = 'user/profile_detail.html'
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
Upvotes: 0
Views: 1250
Reputation: 1
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
Upvotes: 0
Reputation: 53
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)
Upvotes: 1