Search code examples
pythondjangoimagefield

Django show ImageField


I have extended the base User from Django with the OneToOne method.

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE)
    floor = models.CharField(max_length = 100)
    avatar = models.ImageField(upload_to='userimages')

The image is uploaded to media/userimages.

Now, when I try to show the avatar, I am trying this way, but it doesn't show anything.

<img src="media/{{ user.employee.avatar.url }}" alt="">

If I just output user.employee.avatar.url, I get:

'media/userimages/name.jpg'

The image exists in that folder, but it doesn't appear on the website.

I really can't figure out why it doesn't work. Any help is appreciated.


Solution

  • I finally figured out how to make it work, so just in case somebody else has the same problem I am going to answer to my question. Basically just add this to settings.py

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

    And this to urls.py:

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