簡體   English   中英

在 django 的個人資料中顯示用戶的帖子

[英]Display user's posts in their profile on django

我一直試圖讓用戶的個人資料頁面有用戶的帖子,但每次我運行我的代碼時,什么都沒有顯示只有用戶的用戶名和用戶的 email。 我已經嘗試了多種方法來使其工作,但不知何故它沒有。 我認為 profile.html 中有錯誤。

視圖.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})

模型.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)

配置文件.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>

這里的問題在於這條線:

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

要從登錄用戶那里獲取帖子,您需要使用以下命令:

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

要從所選用戶那里獲取帖子,您需要執行以下操作:

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

我希望這有幫助:)

您正在查詢錯誤的列:

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

posti是一個ImageField 您實際上想要查詢user字段:

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

話雖如此,您的視圖中不需要任何這些查詢。 您可以簡單地使用您的related_name ,即:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM