Django用户帖子将从所有帖子中过滤并显示在用户个人资料中

时间:2017-06-22 08:02:31

标签: python django django-models django-templates django-views

我是Python和Django的新手,现在开发博客。我有这个模型,用户可以登录到网站并添加他们的帖子,所有帖子都显示在家里。同时我希望用户的帖子显示在用户个人资料中。

我的博客文章是

from django.db import models
from django.utils import timezone

class Blogpost(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return self.title

和views.py:

views.py    

from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from blogpost.models import Blogpost

def home(request):
    context = {}
    template = 'home.html'
    return render(request,template,context)

def about(request):
    context = {}
    template = 'about.html'
    return render(request,template,context)

@login_required(login_url='/accounts/login/')
def userprofile(request):
    user = request.user
    context = {'user': user}
    user_posts=Blogpost.objects.filter(author=request.user).order_by('-published_date')
    template = 'profile.html'
    return render(request,template,context,{'user_posts':user_posts})

我正在使用此模板显示查询集返回的用户的帖子。

profile.html

{% extends 'base.html' %}
{% load staticfiles %}

{% block blogprofile %}

        {{ user.username }}
        {{ user.email }}

    {% for Blogpost in user_posts %}
            <div class="post">

                <div class="date">
                    <p>{{ Blogpost.published_date }}</p>
                    <p>{{ Blogpost.author }}</p>
                </div>

                <h1><a href="{% url 'post_detail' pk=Blogpost.pk %}">{{ Blogpost.title }}</a></h1>
                <p>{{ Blogpost.text|linebreaksbr }}</p>

            </div>
    {% endfor %}

{% endblock %}

现在,当我打开profile.html时,我只收到用户名和电子邮件,因为帖子没有被检索到。任何人都可以在我犯错的地方纠正我。

1 个答案:

答案 0 :(得分:1)

将您的观点更改为:

@login_required(login_url='/accounts/login/')
def userprofile(request):
    user = request.user
    user_posts = Blogpost.objects.filter(author=request.user).order_by('-published_date')
    template = 'profile.html'
    return render(request, template, {'user_posts':user_posts,'user': user})