1

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

我想列出由现在登录的用户创建的帖子。如果“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/')

谢谢你。

4

1 回答 1

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

于 2012-08-25T16:38:00.900 回答