1

I would like to display an image in function of my views. For Example if I have value in my database "100" for a user, my website show me a specific Image if the value is not "100" it shows me another Image. I wrote a simple code with "print" but I do not know how replace "print" with an image and then display it on my page.

this my views.py

def Test(request):
if request.user.is_authenticated:
    try:
        name = coach.objects.get(user=request.user)
    except coach.DoesNotExist:
        name = coach(user=request.user)
    objs = Lesson.objects.all().filter(mycoach = name)
    args = {'objs': objs}
    if name.monday=="100":
        print("Monday")
    else:
        print("Not Monday")
    messages.add_message(request, messages.INFO, 'Welcome to your profile')
    return render(request, 'test.html', args)
else:
    return render(request, 'home.html')
Nikita
  • 75
  • 1
  • 10
  • You probably want to use a 'context variable'. They are stored in a 'context' dictionary in your view and then they can be used by your template. Have a look at https://stackoverflow.com/questions/20957388/what-is-a-context-in-django – Tom Dalton Jun 21 '18 at 10:59
  • In your case, your template's context dict is the variable `args`. By convention you might want to rename that 'context'. Add the image file name you want to use in that dict, and then use that image file name in your template. – Tom Dalton Jun 21 '18 at 11:00

1 Answers1

1

You can do like below

def Test(request):
  if request.user.is_authenticated:
    try:
        name = coach.objects.get(user=request.user)
    except coach.DoesNotExist:
        name = coach(user=request.user)
    objs = Lesson.objects.all().filter(mycoach = name)
    args = {'objs': objs}
    if name.monday=="100":
       args['image_url'] = 'https://www.google.com/photos/about/static/images/google.svg' 
    else:
        args['image_url'] = 'http://cdn1.itpro.co.uk/sites/itpro/files/styles/article_main_wide_image/public/images/dir_248/it_photo_124192.jpg?itok=ey4UVXkQ'
    messages.add_message(request, messages.INFO, 'Welcome to your profile')
    return render(request, 'test.html', args)
else:
    return render(request, 'home.html')

home.html

{% if image_url %}
    <img src="{{image_url}}" alt=""/>
{% endif %} 

relace image urls with your's.

anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62