Django доступ к полям модели с отношением многие ко многим - PullRequest
0 голосов
/ 06 мая 2020

Итак, у меня есть следующие модели:

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')

В моих представлениях я создал такой объект сообщения:

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

Теперь мне нужно отобразить поле изображения Модель изображения на моей домашней странице. Я пытаюсь сделать это так:

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

Но это возвращает изображение с src = (unknown). Итак, мой вопрос: как мне получить доступ к полю изображения модели изображения?

EDIT: вот мой 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('../')

И моя форма:

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

1 Ответ

0 голосов
/ 06 мая 2020

Нашел как исправить. В моем html я звонил {{post.images.image}}. Вместо этого мне нужно вызвать {{post.images.all}}, чтобы получить все модели изображений, а затем для каждой из них, которые мне нужны, чтобы получить изображение. Поэтому вместо

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

мне нужно сделать

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