Display profile pic from model in template in django

a 夏天 提交于 2019-12-08 09:48:14

问题


I want to insert the user's image in the img src field.But I'm not able to do it. My code:

models.py

class allusers(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    avatar = models.ImageField(upload_to='retest/static/images/')

views.py

u = User.objects.get(username=username)

tempate

<img src={{ u.allusers.avatar }}

回答1:


1, register static and media in settings correct way .

MEDIA_URL = '/media/'
MEDIA_ROOT = '/srv/django/myproject/src/myproject/media'
STATIC_URL = '/static/'
STATIC_FILE_ROOT = '/srv/django/myproject/src/myproject/static'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    '/srv/django/myproject/src/myproject/static',
)

2, call static and media urls in urls.py

from django.views.static import serve

url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT}), 
url(r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_FILE_ROOT}),

3, Call avathar like this

<img src="{{ u.allusers.avatar.url }}" alt="Avathar"/>



回答2:


You need to use the attibutes name, in that way:

<img src={{ u.allusers.avatar.url }}

Can check it in documentation.

Note: that will works if u.allusers is a good reference, of which I have some doubt.




回答3:


You need to use related_name in the OneToOne field to reference the allusers model through User.

 class allusers(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")

template

<img src="{{ u.profile.avatar.url }}">



回答4:


Actually I got an alternate solution

settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

urls.py

from django.conf.urls.static import static
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, 
document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, 
document_root=settings.MEDIA_ROOT)


来源:https://stackoverflow.com/questions/43720099/display-profile-pic-from-model-in-template-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!