Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
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 }} />
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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"/>
about 4 years ago · Santiago Trujillo Report

0

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)
about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!