boyenec
boyenec

Reputation: 1617

Django ajax how to get object image src link?

I am implementing ajax in my list views page. Now I am facing problems for rendering image. How to get my image src link of each object ?

views.py:

class PostJsonListView(View):
    def get(self, *args, **kwargs):
        print(kwargs)
        upper = kwargs.get('num_posts')
        lower = upper - 1 
        posts = list(Blog.objects.values('id','title','body','blog_header_image')[lower:upper])
        posts_size = len(Blog.objects.filter(is_published='published'))
        max_size = True if upper >= posts_size else False
        return JsonResponse({'data':posts,'max': max_size},safe=False)

.html

  <div class="card mb-4" id="card mb-4"></div>



    <script>
    
    
    const postsBox = document.getElementById('card mb-4')
    console.log(postsBox)
    const spinnerBox = document.getElementById('spinner-box')
    const loadBtn = document.getElementById('load-btn')
    const loadBox = document.getElementById('loading-box')
    let visible = 1 
    
    const handleGetData = () => {
        $.ajax({
            type: 'GET',
            url: `/posts-json/${visible}/`,
            success: function(response){
                maxSize = response.max
                const data = response.data
                spinnerBox.classList.remove('not-visible')
                setTimeout(()=>{
                    spinnerBox.classList.add('not-visible')
                    data.map(post=>{
                        console.log(post.id)
                        postsBox.innerHTML += `<img class="img-fluid rounded"  style="max-height:1000px;max-width:1200px;" src="" alt="..." />`
                    })
                    if(maxSize){
                        console.log('done')
                        loadBox.innerHTML = "<h4>No more posts to load</h4>"
                    }
                }, 500)
            },
            error: function(error){
                console.log(error)
            }
        })
    }
    
    handleGetData()
    
    loadBtn.addEventListener('click', ()=>{
        visible += 3
        handleGetData()
    })
    
    
    </script>    
         

How to get object href so user can click an view the details page? also how to render image url?

Upvotes: 0

Views: 349

Answers (1)

Ahtisham
Ahtisham

Reputation: 10116

When getting image url by using values() in django you will not get the path of your image to get path you need to prepend your MEDIA_URL for each object like this:

from django.conf import settings

posts = list(Blog.objects.values('id','title','body','blog_header_image')[lower:upper])
for post in posts:
     post['blog_header_image'] = settings.MEDIA_URL + post['blog_header_image']

and then in your javascript you can access the image like this:

postsBox.innerHTML += "<img ... src="+post.blog_header_image+"</>"

Or you could do it like this:

 posts = list(Blog.objects.all()[lower:upper])
 data = list()
 for post in posts:
     data.append({'id': post.id, 'title': post.title, 'image_url': post.blog_header_image.url})

 return JsonResponse({'data':data,'max': max_size},safe=False)

And then in javascript:

 postsBox.innerHTML += "<img ... src="+post.image_url+"</>"

Upvotes: 1

Related Questions