简体   繁体   English

如何查找 Django ImageField URL

[英]How to Find Django ImageField URL

I'm trying to accomplish something I believed would be simple: upload an image (via admin), then use the complete URL in a template to display the image.我正在尝试完成我认为很简单的事情:上传图像(通过管理员),然后在模板中使用完整的 URL 来显示图像。

The problem is I can only print the relative URL: /pics/filename.jpg.问题是我只能打印相对 URL:/pics/filename.jpg。 I believe the sequence is settings.py (MEDIA_ROOT, MEDIA_URL), urls.py, views.py and then mytemplate.html.I hope someone can find what's missing.我相信顺序是 settings.py (MEDIA_ROOT, MEDIA_URL)、urls.py、views.py 然后是 mytemplate.html。我希望有人能找到缺少的东西。

Settings:
 STATIC_URL = '/static/'
 MEDIA_ROOT = '/Users/ed/code/projects/djcms/pics/'
 MEDIA_URL = '/pics/'

Urls.py:网址.py:

from django.conf import settings
from django.conf.urls.static import url, static

from . import views

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^news/(?P<pk>[0-9]+)/$', views.detail, name='detail'),
] + static(r'^$/pics/', document_root = settings.MEDIA_URL)

Views.py视图.py

def detail(request, pk):
    story = Article.objects.get(pk=pk)
    my_pic = Photo.objects.get(pk=pk)
    print(story.image.url)
    print(my_pic)
    print(story.body)


    print(request)
    context = {'story': story}
    return render(request, 'articles/detail.html', context)

The Error with story.image.url: story.image.url 的错误:

AttributeError: 'Photo' object has no attribute 'url'

When I remove the .url, I get this partial URL:当我删除 .url 时,我得到了这个部分 URL:

pics/intro-bg.jpg

What am I missing?我错过了什么? Thanks.谢谢。

This setup is working for me, maybe it will help you.这个设置对我有用,也许它会帮助你。 It is for latest version of Django.它适用于最新版本的 Django。 Many answers in OS are for older Django versions.操作系统中的许多答案都是针对较旧的 Django 版本。

URLS:网址:

urlpatterns = [
#url
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Settings:设置:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Template:模板:

<img src="{{ foo.image.url }}"><br>

Model:模型:

image = models.ImageField(upload_to = 'img/', default = 'img/None/no-img.jpg')

My foo model has an imagefield, when it is stored, I can retrieve the full url through item.image.url based on the above setup.我的 foo 模型有一个图像字段,当它被存储时,我可以根据上面的设置通过item.image.url检索完整的 url。

在 urls.py 中,尝试: static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

The URLS seem to be causing the problem. URLS 似乎是导致问题的原因。

from django.conf import settings
from django.conf.urls.static import url, static

from . import views

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^news/(?P<pk>[0-9]+)/$', views.detail, name='detail'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

The logic behind those URL patterns displays my homepage and individual news articles.这些 URL 模式背后的逻辑显示我的主页和个别新闻文章。 Each news article has a url of /news/, followed by the article number, ie /news/1.每篇新闻文章的url为/news/,后跟文章编号,即/news/1。

Each article uses my Photo model via a ForeignKey in the Article model.每篇文章都通过文章模型中的外键使用我的照片模型。 This allows a photo to be tied to a specific article.这允许将照片绑定到特定文章。

However, in my template, the URL is a jumble of news and images:但是,在我的模板中,URL 是一堆新闻和图片:

http://localhost:8000/news/2/img/phones.png. 

The news URL correctly finds the news item but not the image associated with the news item.新闻 URL 正确地找到了新闻项目,但没有找到与新闻项目相关联的图像。 The correct result would display the individual article along with its associated image.正确的结果将显示单个文章及其关联的图像。 Do I need another URL?我需要另一个网址吗?

The Request object in Django has a method, build_absolute_uri() Using this method you can get absolute url of the image field. Django 中的Request 对象有一个方法, build_absolute_uri()使用这个方法可以得到图片字段的绝对url。

So to get the absolute url, you can use two methods所以要获取绝对url,可以使用两种方法

First method: Getting absolute url in view while doing GET request.第一种方法:在执行 GET 请求时在视图中获取绝对 url。

from settings import MEDIA_URL

class ClassName(APIView):

    def get(self, *args, **kwargs):
        model = models.ModelName.objects.get(name='pran')
        absolute_url = self.request.build_absolute_uri('/').strip("/") + MEDIA_URL + str(model.image_field_name)
        return Response({'url': absolute_url}, 200)

Method 2: If you are doing POST request and you are using serializer then pass request as context object to it.方法 2:如果您正在执行 POST 请求并且您正在使用序列化程序,则将请求作为上下文对象传递给它。

ser = serializers.MySerializerName(data=request.data}, context={'request': request})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM