Django - 登录用户帖子的列表

时间:2012-08-25 16:13:54

标签: django django-models django-views

有一个博客项目。它现在正常工作。会有多个用户。

我想列出由用户现在登录创建的帖子。如果'x'用户登录,他必须在管理页面上看到自己的帖子。

这是正确的方法吗?

这是我的models.py:

class Post(models.Model):
    title = models.CharField(max_length = 100)
    body = models.TextField()
    slug = AutoSlugField(populate_from='title',unique=True)
    posted = models.DateField(auto_now_add=True)
    isdraft = models.BooleanField(default=False)

    def __unicode__(self):
        return self.title()

    @permalink
    def get_absolute_url(self):
        return ('view_blog_post',None, {'postslug':self.slug})


class UserProfile(models.Model):
    user = models.OneToOneField(User)

def create_user(sender,instance,created,**kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user, sender=User)

和我的views.py(只是管理页面的一部分):

@login_required(login_url='/panel/')
def adminView(request):
    if request.session['loggedin']=="djangoo":

        draft_list = Post.objects.filter(isdraft=True).order_by("-posted")
        p_draft = Paginator(draft_list,15)

        publish_list = Post.objects.filter(isdraft=False).order_by("-posted")
        p_publish = Paginator(publish_list,15)

        page = request.GET.get('page')

        try:
            post_d = p_draft.page(page)
            post_p = p_publish.page(page)
        except PageNotAnInteger:
            post_d = p_draft.page(1)
            post_p = p_publish.page(1)
        except EmptyPage:
            post_d = p_draft.page(p_draft.num_pages)
            post_p = p_publish.page(p_publish.num_pages)


        return render_to_response('admin.html',
                                  {'draft_list':draft_list,'publish_list':publish_list,'post_d':post_d,'post_p':post_p},
                                 context_instance=RequestContext(request))
    else:
        HttpResponseRedirect('/panel/')
谢谢。

1 个答案:

答案 0 :(得分:2)

您必须存储在帖子模型中发布的用户,然后您可以轻松过滤掉这些内容。

我会更新模型:

class Post(models.Model):
    owner = models.ForeignKey('User')
    # your other fields

管理员观点:

@login_required(login_url='/panel/')
def adminView(request):
    draft_list = Post.objects.filter(owner=request.user).filter(isdraft=True).order_by("-posted")
    #------------------------------^^^^ filter based on owner
    p_draft = Paginator(draft_list,15)

    publish_list = Post.objects.filter(owner=request.user).filter(isdraft=False).order_by("-posted")
    p_publish = Paginator(publish_list,15)
    #your other view code
    ...

此外,您还必须更新添加帖子以放置owner的视图。