问题
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.
回答1:
You should not use
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
to do this. This is okay only for debug purposes. Otherwise, it's your nginx/apache/other_server that should be responsible for serving static files and media files along with routing the .sock file generated by gunicorn/uwsgi.
回答2:
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)
来源:https://stackoverflow.com/questions/49035290/django-show-imagefield