python - Django:如何根据views.py中的功能显示不同的图像

标签 python django image view

我想根据我的观点显示图像。例如,如果我的数据库中某个用户的值为“100”,我的网站会向我显示一个特定的图像,如果该值不是“100”,它会向我显示另一个图像。我用“打印”编写了一个简单的代码,但我不知道如何用图像替换“打印”,然后将其显示在我的页面上。

这是我的观点.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')

最佳答案

你可以像下面这样做

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

将图像网址替换为您的图像网址。

关于python - Django:如何根据views.py中的功能显示不同的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50966797/

相关文章:

python - 下划线 _ 作为 Python 中的变量名

django 管理员 : queryset filter not working

python - MySQL 配置不当原因 : unsafe use of relative path

python - "variable//= a value"语法在 Python 中意味着什么?

python - Django channel 不发送回复消息

python - 将两个数据帧中的列合并为一个

django - 为 Django 静态文件提供服务时的 Apache 403

java - 将图标设置为 JLabel - 不显示图标

java - 单击按钮显示图像

javascript - 在 Coinflip 游戏中切换图像