Looking For Help To Get Profile Image Into Blog Posts

Hi,

Im looking to retrieve a users profile image into the blog post template and was looking for the best way to do this.

I have the following models:


class Profile(models.Model):

    # Define Fields For Model
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="profile") # Delete profile when user is deleted
    avatar = models.ImageField(default='profile_images/default.png', upload_to='profile_images')

  class Post(models.Model):
      title = models.CharField(max_length=200, unique=True)
      slug = models.SlugField(max_length=200, unique=True)
      author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
      updated_on = models.DateTimeField(auto_now= True)
      content = models.TextField()
      created_on = models.DateTimeField(auto_now_add=True)
      status = models.IntegerField(choices=STATUS, default=0)

    class Meta:
        ordering = ['-created_on']

    def __str__(self):
        return self.title

Template

{% for post in post_list %}
<div class="card mb-4">
    <div class="card-body">
        {{ post.author.profile.avatar.url }}
        <h2 class="card-title">{{ post.title }}</h2>
        <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p>
        <p class="card-text">{{post.content|slice:":200" }}</p>
        <a href="{% url 'post_detail' post.slug  %}" class="btn btn-primary">Read More &rarr;</a>
    </div>
</div>
{% endfor %}

Im looking to get the correct syntax for the post.author.profile.avatar.url to get the user profile picture in

Thanks in advance
Rob

The issue here is that by using a ForeignKey to User in your Profile model, you have created a Many-to-One relationship between them. A User could have many Profile.

For your reference to the image to work, you’d need to identify which profile to use.

Now, you can work around this - there are a couple of options here to resolve this.

But, I’m going to guess that the real solution would be to change the relationship (and therefore the field definition) to be a OneToOneField.

If you really want a user to have multiple profiles, then you do need to address this a different way - and if that’s the case, let us know.

Hi Ken thanks for this all working with the one to one