najmath
najmath

Reputation: 261

Display profile pic from model in template in Django

I want to insert the user's image in the src field of img tag.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)

template

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

Upvotes: 2

Views: 5149

Answers (4)

najmath
najmath

Reputation: 261

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)

Upvotes: 1

mking
mking

Reputation: 129

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 }}">

Upvotes: 0

SOBIR N
SOBIR N

Reputation: 346

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"/>

Upvotes: 6

LlaveLuis
LlaveLuis

Reputation: 88

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.

Upvotes: 0

Related Questions