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, })
CodePudding user response:
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