如何从一个Django模型访问图像URL到另一个模型?如何将其放在模板上?
我正在使用两个模型论坛
和用户
。
我想访问用户
'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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是简单的关系。要获取图像的URL,您需要在图像对象上添加
.url
。只是使用:It is simple relation. To get url of an image you need to add
.url
on the Image object. Just use: