1

I am trying to display an image from an imagefield in Django. The imagefield works correctly. I can save an image to local storage, but the problem is that when the server is running, I see a url in the place of the imagefield. I'm guessing it should be a url to the image, but when I click on it, it just reloads the current page. How can I make it so that when I click on it, I am taken to a page with the image? This is how I have tried doing it, but it doesn't work:

#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)
Zelda
  • 47
  • 1
  • 10

2 Answers2

2

To make any url work you first need to add it properly to the urls.py

Add MEDIA_URL and MEDIA_ROOT to settings.py:

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

Create 'uploaded_files' in the root of your project.

Add new links to 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)

Display as this:

<img src="{{ object.image.url }}"/>
vladimir.gorea
  • 641
  • 1
  • 8
  • 27
1

You should be able to use the url attribute, documented here https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.fields.files.FieldFile.url.

In your template you can do:

<!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>

In order to make the image link to itself:

<a href="{{ image.url }}">
    <img src="{{ image.url }}">
</a>
Jafnee
  • 23
  • 6