Search code examples
djangomany-to-manyfield

Django access fields of model with many to many relationship


So I have the following models:

class Image(models.Model):
    image=models.ImageField(upload_to='postimages')
    id=models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)

class Post(models.Model):
    title=models.CharField(max_length=500)
    created_date=models.DateField(auto_now=True)
    id=models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
    images=models.ManyToManyField(Image)
    user=models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, related_name='posts')

In my views I have created a post object like this:

post=Post(title=title)
post.save()
post.images.add(image)

Now I need to diplay the image field of the Image model in my homepage. I am trying to do it like this:

{%for post in posts%}
    <img src="{{post.images.image}}">
{%endfor%}

But this returns image with src=(unknown). So my question is how do I access the image field of the Image model?

EDIT: Here is my views.py

def addpost(request):
    imageform=ImageForm()
    postform=PostForm()
    if request.method=="POST":
        imageform=ImageForm(request.POST, request.FILES)
        postform=PostForm(request.POST)
        if imageform.is_valid() and postform.is_valid():
            #add the image and the post to the database
            image=Image(image=request.FILES['image'])
            image.save()
            title=request.POST['title']
            post=Post(title=title)
            post.save()
            post.images.add(image)
    return redirect('../')

And my form:

    <form method="post" action="{%url 'addpost'%}" enctype="multipart/form-data">
        {%csrf_token%}
        {{imageform}}
        {{postform}}
        <button type="submit">Post</button>
    </form>

Solution

  • I found how to fix it. In my html I was calling {{post.images.image}}. Instead I need to call {{post.images.all}} to get all image models and then for every single one I need to get the image. So instead of

    {%for post in posts%}
        <img src="{{post.images.image}}">
        <p>{{post.title}}</p>
    {%endfor%}
    

    I need to do

    {%for post in posts%}
        {%for image in post.images.all%}
            <img src="{{image.image}}">
        {%endfor%}
        <p>{{post.title}}</p>
    {%endfor%}