如何从一个 Django 模型访问图像 URL 到另一个?我如何将它放在模板上?

How do I access image URL from one django model to another? How do I put it on a template?

我正在使用两个模型 ForumUser

我想访问 Userprofile_img 的 url 并将其显示到我在 Forum 中的模板中。我应该如何在 Forummodel.py 中对此进行编码?

User model.py:

class User(models.Model):
    first_name = models.CharField(max_length=100)
    middle_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    profile_img = models.ImageField(upload_to='images/', null=True, blank=True)

Forum model.py:

class Forum(models.Model):
    post_title = models.CharField(max_length=100)
    post_body = models.TextField()
    pub_date = models.DateField(auto_now_add=True)
    author = models.ForeignKey(User, default=None, on_delete=models.CASCADE, null=True)
    forum_id = models.AutoField(primary_key=True)

    def __str__(self):
        return 'Title: {}, dated {}.'.format(self.post_title, self.pub_date)

Forum views.py:

def View_Forum(request):
    forum_posts = Forum.objects.all().order_by("-pub_date")
    return render(request, "forums.html", {"forum_posts": forum_posts, })

是简单的关系。要获取图像的 url,您需要在图像对象上添加 .url。只需使用:

forum.author.profile_img.url