Django中如何在首页仅展示当前登录用户的文章?
Hey there! Let's get your homepage displaying only the posts created by the currently logged-in user. Here are two solid approaches based on your existing code:
Option 1: Function-Based View (completing your index view)
Since you started with a function view, let's finish that up. We'll use the request.user object to filter posts, and optionally add login protection:
from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Post @login_required # Uncomment this if you want to redirect non-logged-in users to login page def index(request): # Filter posts to only those authored by the current user # Add status='published' inside the filter if you only want to show published posts user_posts = Post.objects.filter(author=request.user).order_by('-publish') # Pass the filtered posts to your template using the variable name you already have ('deeppost') return render(request, 'home.html', {'deeppost': user_posts})
Notes for this option:
- The
@login_requireddecorator ensures only logged-in users can access this view (they'll be redirected to the login page if not authenticated). If you want non-logged-in users to see the "not logged in" message from your template, remove this decorator and keep theif request.user.is_authenticatedcheck in the template. - The
order_by('-publish')maintains the descending order from your model's Meta class, showing newest posts first.
Option 2: Class-Based ListView (using the imported ListView)
If you prefer using class-based views (which are great for list displays), here's how to customize it to filter by the current user:
from django.views.generic import ListView from django.contrib.auth.mixins import LoginRequiredMixin from .models import Post class HomeListView(LoginRequiredMixin, ListView): model = Post template_name = 'home.html' context_object_name = 'deeppost' # Matches the variable name in your template ordering = ['-publish'] # Same as your model's default ordering def get_queryset(self): # Override the queryset to only include posts by the current user queryset = super().get_queryset() # Add .filter(status='published') here if you only want published posts return queryset.filter(author=self.request.user)
Update your URLs
Whichever view you choose, you'll need to add it to your urls.py:
- For the function view:
path('', views.index, name='home') - For the class-based view:
path('', views.HomeListView.as_view(), name='home')
Quick Template Fix
I noticed a stray closing anchor tag </a> in your template loop — you should remove that to avoid invalid HTML:
<!-- Before --> <li>{{post.title}}</li></a><p>{{post.body}}</p>Created by- {{post.author}} <!-- After --> <li>{{post.title}}</li><p>{{post.body}}</p>Created by- {{post.author}}
That's it! Now your homepage will only show posts created by the logged-in user.
内容的提问来源于stack exchange,提问作者Deep Jhavar

