【问题标题】:viewing images from django models从 django 模型中查看图像
【发布时间】:2019-11-20 06:39:16
【问题描述】:

我正在尝试将图像添加到我的投票应用程序,我已将其设置为:upload_to='mysite/static/polls_app/question_pics'

但是当我查看页面时使用了错误的文件路径: GET /polls/1/static/polls_app/question_pics/

我该如何编辑它,以便 Django 使用保存图像的 url?

模型.py

    question_image = models.ImageField(upload_to='static/polls_app/question_pics', default=None, blank=True, null=True)
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

Views.py

    model = Question
    template_name = 'polls_app/detail.html'

detail.html


<img src="{{ question.question_image.url }}" alt="image">

urls.py

    path('<int:pk>/', views.DetailView.as_view(), name='detail'),

【问题讨论】:

    标签: django-models django-templates django-views


    【解决方案1】:

    在urls.py下面添加

    从 django.views.static 导入服务 从 django.urls 导入包含,re_path 从 。导入设置

    // 你的代码原样

    urlpatterns += [re_path(r'^media/(?P.*)', serve, {'document_root': settings.MEDIA_ROOT})]

    这应该会有所帮助!

    【讨论】:

      猜你喜欢
      • 2019-10-08
      • 1970-01-01
      • 2014-09-15
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 2015-02-28
      相关资源
      最近更新 更多