【问题标题】:Using Django to display images使用 Django 显示图像
【发布时间】:2023-04-01 11:03:01
【问题描述】:

我正在尝试使用 Django 从大量用户提交的图像中显示 3 个随机图像。每张图片都有其他相关的值,就像作者一样,所以我一直在让每张图片成为一个模型,其中的图片字段包含图片本身。不幸的是,我不知道如何从该列表中随机选择并将其传递到 .html 页面以正确显示它。


到目前为止,我已经能够将用户提交的图片保存为模型并提交到文件夹 /media/images/
我的 views.py 将从该文件夹中抓取 3 张随机且唯一的图片,如下所示:

def home_view(request):
    form = MForm(request.POST or None)
    if form.is_valid():
        form.save()

    message_list = MModel.objects.all()

    #Get first random file
    file1choice = random.choice(os.listdir(DIR))

    #Get second random file
    file2choice = random.choice(os.listdir(DIR))
    while(file2choice == file1choice):
        file2choice = random.choice(os.listdir(DIR))

    #Get third random file
    file3choice = random.choice(os.listdir(DIR))
    while(file3choice == file1choice or file3choice == file2choice):
        file3choice = random.choice(os.listdir(DIR))


    context = {
        'file1': file1choice,
        'file2': file2choice,
        'file3': file3choice,
    }

    return render(request, "home.html", context)



在用户看到的 .html 文件中,我访问每个传递的图像,如下所示:
<img src="/media/images/{{ file1 }}" width="300" height="180" alt="">


不幸的是,这不允许我实际访问图像本身的模型,这意味着我也无法显示图像的关联值。我只是在使用 python 抓取随机的东西。


所以,我的问题是 如何将 3 个随机图像模型传递给 .html 文件,以及如何在 .html 本身中显示它?



模型.py

from django.db import models

class MModel(models.Model):
    Message = models.TextField(max_length=200)
    Img = models.ImageField(upload_to='images/')
    Author = models.CharField(max_length=50)

forms.py

from .models import MModel
from django import forms

class MForm(forms.ModelForm):
    class Meta:
        model = MModel
        fields = ['Message', 'Img', 'Author']

【问题讨论】:

    标签: python html django django-models


    【解决方案1】:

    我发现我可以传入随机选择的对象本身,

    #Some uniquely random file 1
    choice1 = random.choice(message_list)
    
    #Some uniquely random file 2
    choice2 = random.choice(message_list)
    while(choice2 == choice1):
        choice2 = random.choice(message_list)
    
    #Some uniquely random file 3
    choice3 = random.choice(message_list)
    while(choice3 == choice1 or choice3 == choice2):
        choice3 = random.choice(message_list)
    


    这意味着我可以像这样在 .html 中访问对象的图像(和其他属性):
    <img src="/media/{{ aPassedFile.Img }} " width="290" height="180" alt="">

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多