我正在尝试在Django的图像场中显示图像。图像域正常工作。我可以将图像保存到本地存储,但问题是当服务器运行时,我会在图像域的位置看到一个URL。我猜它应该是图像的网址,但是当我点击它时,它只是重新加载当前页面。我怎样才能这样做,当我点击它时,我被带到一个带有图像的页面?这就是我尝试过的方法,但它不起作用:
#views.py
class CreateView(generics.ListCreateAPIView):
"""This class defines the create behaviour of our REST Api"""
queryset = BucketList.objects.all()
serializer_class = BucketListSerializerPostOnly
def perform_create(self, serializer):
"""Save post data when creating a new bucketlist"""
serializer.save()
class DetailsView(generics.RetrieveUpdateDestroyAPIView):
"""This Class handles the http GET, PUT, and DELETE requests"""
queryset = BucketList.objects.all()
serializer_class = BucketListSerializer
# shows image in a new tab?
def show_image(request, img):
context = {
'image': img
}
return render(request, 'images.html', context)
# my html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="/media/documents/{{ image }}">
<a href="/">Go Back</a>
</body>
</html>
# urls.py
urlpatterns = [
url(r'^bucketlist/$', CreateView.as_view(), name='create'),
url(r'^', CreateView.as_view(), name='create'),
url(r'^bucketlist/(?P<pk>[0-9]+)/$', DetailsView.as_view(), name='details'),
url(r'^media/documents/(?P<img>[\w\-]+)/$', views.show_image,
name='view_image')
]
urlpatterns = format_suffix_patterns(urlpatterns)
答案 0 :(得分:0)
您应该可以使用url
中记录的<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="{{ image.url }}">
<a href="/">Go Back</a>
</body>
</html>
属性。
在您的模板中,您可以:
<a href="{{ image.url }}">
<img src="{{ image.url }}">
</a>
为了使图像链接到自身:
Pipenv
答案 1 :(得分:0)
要使任何网址正常工作,您首先需要将其正确添加到urls.py
将MEDIA_URL和MEDIA_ROOT添加到settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_files')
MEDIA_URL = '/media/'
在项目的根目录中创建“ uploaded_files”。
将新链接添加到urls.py
from . import views, settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
显示为:
<img src="{{ object.image.url }}"/>