Juan Martin Zabala
Juan Martin Zabala

Reputation: 801

Display user's posts in their profile on django

I have been trying to make the profile page of a user have the user's posts but everytime I run my code nothing shows up only the user's username and user's email. I've tried multiple ways to make it work but somehow it doesn't. I think the profile.html has the error in it.

views.py

    def profile(request, pk=None):
        if pk:
            post_owner = get_object_or_404(User, pk=pk)
            user_posts=Post.objects.filter(posti=request.user)

        else:
            post_owner = request.user
            user_posts=Post.objects.filter(posti=request.user)
        return render(request, 'profile.html', {'post_owner': post_owner, 'user_posts': user_posts})

models.py

    class Post(models.Model):
        text = models.CharField(max_length=200)
        posti = models.ImageField(upload_to='media/images', null=True, blank="True")
        user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default=2)

profile.html

    <div class="content-section">
      <div class="media">
        <img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
        <div class="media-body">
          <h2 class="account-heading">{{ post_owner.username }}</h2>
          <p class="text-secondary">{{ post_owner.email }}</p>
        </div>
        {% for Post in user_posts %}
          <li class="list-group-item">{{ Post.text }}
            <a href="{% url 'profile_pk' pk=image.user.pk %}">{{ Post.user }}</a>
            {% if Post.posti %}
              <img src="{{ image.posti.url }}" alt="image here" style="max-width: 300px; max-height: 300px">
            {% endif %}
            {% if Post.user == user %}
              <div class="float-right">
                <form action="delete_image/{{ image.id }}/" action="post">
                  <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
                </form>
              </div>
            {% endif %}
          </li>     
        {% endfor %}
      </div>
    </div>

Upvotes: 0

Views: 2696

Answers (2)

Selcuk
Selcuk

Reputation: 59184

You are querying the wrong column:

user_posts=Post.objects.filter(posti=request.user)

posti is an ImageField. You actually want to query the user field:

user_posts=Post.objects.filter(user=request.user)

That being said, you don't need any of these queries in your view. You can simply make use of your related_name, i.e.:

{% for Post in post_owner.imageuser.all %}

Upvotes: 0

tim-mccurrach
tim-mccurrach

Reputation: 6815

The problem here is with the line:

user_posts=Post.objects.filter(posti=request.user)

To get the posts from the logged in user you will need to use this:

user_posts=Post.objects.filter(user=request.user)

and to get the posts from the selected user you will need to do this:

user_posts=Post.objects.filter(user_id=pk)

I hope this helps :)

Upvotes: 1

Related Questions