0

I have image in my applications directory. I want to use this image in my template. I use Ajax request for getting path of image and i want to show image in template. How i can do it? My code:

def posts(request):
if request.is_ajax():
    offset = request.GET.get('offset')
    limit = request.GET.get('limit')
    all_posts = Post.objects.all().order_by('-pub_date')[offset:limit]
    if all_posts:
        data = []

        for obj in all_posts:
            # image = PostImage.objects.filter(pk=obj.pk)
            image = obj.postimage_set.all()
            js = {
                'info': 'success',
                'id': obj.pk,
                'title': obj.title,
                'description': obj.description,
                'pub_date': obj.pub_date.strftime("%d.%m.%Y %H:%M"),
            }
            if image:
                img = {'image': str(image[0].image)}
            else:
                img = {'image': ''}
            js.update(img)
            data.append(js)
        return HttpResponse(json.dumps(data), content_type='application/json; charset=utf8')
    else:
        return HttpResponse(404)
else:
    return render(request, 'main.html')    
Petr Vasilev
  • 150
  • 14

1 Answers1

0

And what's your problem with this code? And what's the problem with this action?..

To import an image in your template with Ajax, you need to:

  • Make an ajax request to your view function (here : posts)
  • Get the path of your image (so apparently you're ok with that)
  • Return the path to your template with the return of your function
  • Display image as you can see in this question on StackOverFlow

Example:

    $('#list li a').click(function () {
        var url = $(this).attr('href'), //Replace with ajax call to your function
        image = new Image();
        image.src = url;
        image.onload = function () {
            $('#image-holder').empty().append(image); //Replace id
        };
        image.onerror = function () {
            $('#image-holder').empty().html('That image is not available.'); //Replace id
        }

    $('#image-holder').empty().html('Loading...'); //Replace id

    return false;
});
</pre>
Community
  • 1
  • 1
Sanoc
  • 101
  • 1
  • 8