django get id for traverse a list

i want to convert my list into dict to have my id so i try this in my views

def img2(request):

posts = Post.objects.all()
i=[]
for p in posts:
    print(p.id)
    i.append(p.id)
    #post={'id':str(p.id)}
#print(i)
'''def Convert(lst):
    res_dct = {str(lst[i]): lst[i] for i in range(0, len(lst), 1)}
    return res_dct   
# Driver code
d=Convert(i)'''
d = {str(i[k]): i[k] for k in range(0, len(i), 1)}
print(d)
for j in d:
    print(j)
return render(request, 'imgg.html', d)

then i want to display every id in html and this is my html file:

test

{% for n in d %}

{{n}}

{% endfor %}

so.. nothing happened and i don't know what's the problem some help plz and thx a lot in general i have a model form post and another one for images with foreignkey and i want to display every post with first image uploded so i have my db with post and images but i never get the first image to display at home page then i try to make a dict with all post_id with for i will try to display every single image_post for her post if u have another method i will be thankfull ^^

1 answer

  • answered 2021-11-27 16:07 Medheni Benelghali

    this is my views.py:

    from django.shortcuts import render, get_object_or_404
    from django.db.models import Count
    import posts
    
    from .models import Post, PostImage
    
    def blog_view(request):
        posts = Post.objects.all()
        return render(request, 'blog.html', {'posts':posts})
    
    def detail_view(request, id):
        post = get_object_or_404(Post, id=id)
        photos = PostImage.objects.filter(post=post)
        return render(request, 'detail.html', {
            'post':post,
            'photos':photos
        })
    
    def create_post_view(request):
        if request.method == 'POST':
            length = request.POST.get('length')
            title = request.POST.get('title')
            description = request.POST.get('description')
    
            post = Post.objects.create(
                title=title,
                description=description
            )
        
            for file_num in range(0, int(length)):
                PostImage.objects.create(
                    post=post,
                    images=request.FILES.get(f'images{file_num}')
                )
    
        return render(request, 'create-post.html')
    def img(request,id):
        img=PostImage.objects.get(id=id)
        return render(request, 'img.html', {'img':img})
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum