i'm having trouble displaying images on my Djnago admin page.
i read https://stackoverflow.com/questions/2443752/how-to-display-uploaded-images-in-change-list-page-in-django-admin/51181825#51181825
this article but still didn't get what i want :(
this is my codes
models.py
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, PermissionsMixin
)
from django.db import models
from django.utils.html import mark_safe
class User(AbstractBaseUser, PermissionsMixin):
image = models.ImageField(
upload_to='media/profile_image/',
null=True
)
admin.py
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
def image_tag(self, obj): # Here
return format_html(
f'''<a href="{obj.image.url}" target="_blank">
<img
src="{obj.image.url}" alt="{obj.image}"
width="50" height="50"
style="object-fit: cover;"
/>
</a>''')
list_display = ('uid','get_full_name', 'email', 'nickname', 'introduce','image', 'birth','is_active', 'is_superuser', 'date_joined', 'image_tag')
...
this is what i got
the image is in my PROJECTNAME/media/profile_image but i cant' display it on my admin page :(
CodePudding user response:
The problem could be related to your project's settings or how you define the images' display in your admin.py file.
Please check the following:
Make sure you have MEDIA_URL and MEDIA_ROOT set correctly in your settings.py file.
Check that the image file is readable by the server by navigating to the image URL in your browser.
If you are using an S3 bucket for storing images, check that your bucket is configured correctly and that the IAM user has the correct permissions.
In the image_tag method, you are using obj.image which is an instance of
ImageField, you should use obj.image.url
Also check the image_tag method. The format_html function is used to output safe HTML, so the f'' string is unnecessary and can be removed.
Finally, ensure the image_tag method is passed as an attribute to the list_display tuple in the UserAdmin class.
Though if you provide further code from settings and additional details or error logs. We may be able to help you with specific solution.
CodePudding user response:
I solved the problem by adding
if settings.DEBUG:
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
this on my urls.py
sorry for asking what i could solve it my self, but I will left this for someone who might have same problem... thanks