请求django中的用户帖子

时间:2014-12-26 23:57:05

标签: django django-views

我目前正在寻找如何通过经过身份验证的用户请求帖子,以及他们关注的用户或用户关注他们的帖子。到目前为止,我已经能够显示用户关注他们的帖子,但似乎无法获得自动审核用户的帖子

views.py 

    events = post.objects.filter()
    following = request.user.following_set.all().values_list('to_user',
            flat=True)
    events = events.filter(user__in=following)

任何帮助?

3 个答案:

答案 0 :(得分:0)

除非在您的视图中执行类似

的操作,否则没有内置方式
if request.user.is_authenticated():
    events ...
else:
    events ...

答案 1 :(得分:0)

我无法看到您的模型定义,但您需要这样做:

if request.user.is_authenticated():
   events = request.user.user_posts.filter() # authenticated user posts
else:
   events = post.objects.filter() # all posts

user_posts是Django用户模型到帖子模型的related_name。像这样的东西:

from django.contrib.auth.models import User
class Post(models.Model):
   user = models.ForeignKey(User, related_name="user_posts")
   # ...

答案 2 :(得分:0)

# Importing LoginRequiredMixin to push the user to log in.
from django.contrib.auth.mixins import LoginRequiredMixin

# Post Model Importing
from .models import Post

class Timeline(LoginRequiredMixin, ListView):
     template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super(Timeline, self).get_context_data(**kwargs)
        context['posts'] = Post.objects.all()
        return context