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

发布于 2025-01-30 19:29:12 字数 1274 浏览 1 评论 0原文

我正在使用两个模型论坛用户

我想访问用户's profile_img的URL,然后在forum中显示给我的模板。我应该如何在论坛's model.py.py中对此进行编码?

用户 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> forum view .py

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

I am using two models Forum and User.

I wanted to access the url of User's profile_img and display it to my template in Forum. How should I code this in my Forum's model.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, })

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

反目相谮 2025-02-06 19:29:12

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

forum.author.profile_img.url

It is simple relation. To get url of an image you need to add .url on the Image object. Just use:

forum.author.profile_img.url
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文