'child model accesing the parent model feild in django
Hello guys I have one query in my Django project. I Have two models as mentioned below UserProfileInfo and Post. I want to bring profile_Pic in the Post model so that I can call in HTML.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='users1')
portfolio_site = models.URLField(blank=True)
bio = models.CharField(max_length=2000)
profile_pic = models.ImageField(upload_to='profile_pics', blank=True)
def __str__(self):
class Post(models.Model):
author = models.ForeignKey(UserProfileInfo, related_name='users', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.CharField(max_length=2000)
create_date = models.DateTimeField(default=timezone.now())
published_date = models.DateTimeField(blank=True, null=True)
def __str__(self):
return self.title
Solution 1:[1]
You can access the related UserProfileInfo model instance and it's field by following the author ForeignKey
post = Post.objects.get()
profile_pic = post.author.profile_pic
profile_pic_url = post.author.profile_pic.url # For use in your template
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Iain Shelvington |
