【问题标题】:How to retrieve image url saved into models in views如何在视图中检索保存到模型中的图像 url
【发布时间】:2020-07-07 03:51:56
【问题描述】:

我想获取使用 models.py 成功存储在数据库中的图像 URL 现在我想在 views.py 中的字符串变量中获取图像的 url 或位置

我的模型.py

class Document(models.Model):
    document_id = models.AutoField
    document_name = models.CharField(max_length=50, null=False, blank=False, default="")
    document_img = models.ImageField(upload_to='media', default="", blank=False, null=False)
    document_desc = models.CharField(max_length=500, default="", blank=False, null=False)
    document_date = models.DateField()

这里是views.py

def upload(request):
    if request.method == 'POST' and request.FILES['doc_img']:
        document = Document()
        document.document_name = request.POST.get('doc_name')
        document.document_img = request.FILES['doc_img']
        document.document_desc = request.POST.get('doc_desc')
        document.document_date = request.POST.get('doc_date')
        document.save()
        doc = Document.objects.all()
        img_path = doc[0].document_img

        return HttpResponse(img_path) 

    else:
        return HttpResponse('Failed To Upload')

我知道我们可以在 html 模板中显示图片

<img src='{{doc.0.document_img}}'>

但我希望它在 python 变量中

谁能帮帮我

【问题讨论】:

    标签: python django django-models file-upload django-views


    【解决方案1】:

    如果您想要 relative 路径,那么只需执行...

    img_path = doc[0].document_img.url
    

    对于absolute 路径...

    img_path = settings.MEDIA_URL + doc[0].document_img.url
    

    【讨论】:

      【解决方案2】:

      这应该可以完成工作。

      img_path = doc[0].document_img.url
      

      【讨论】:

        猜你喜欢
        • 2017-02-12
        • 2013-05-16
        • 2020-09-06
        • 2018-05-23
        • 2017-01-25
        • 1970-01-01
        • 2016-07-18
        • 2017-07-02
        • 2022-07-05
        相关资源
        最近更新 更多