Django用户任务展示异常:代码逻辑排查求助
Hey there, let's break down why your app isn't showing only the logged-in user's tasks right now—and how to fix it quick.
The Core Problem
Looking at your views.py code:
tasks = Task.objects.filter() return render_to_response('home.html',{'tasks':tasks})
That filter() call with no arguments is pulling every single Task in your database—not just the ones linked to the current user. No wonder all tasks are showing up for everyone!
Step-by-Step Fix
1. Filter Tasks by the Logged-In User
First, you need to narrow down the Task queryset to only those where the username foreign key matches the currently authenticated user. Also, make sure you're using the request object (since it holds the logged-in user's info):
Updated views.py code:
from django.shortcuts import render from django.contrib.auth.decorators import login_required # Add this decorator to ensure only logged-in users can access this view @login_required def your_view_name(request): # Don't forget the request parameter! # Filter tasks where the Task's username (foreign key) equals the logged-in user tasks = Task.objects.filter(username=request.user) # Use render() instead of render_to_response—it automatically includes request context return render(request, 'home.html', {'tasks': tasks})
2. Quick Model Cleanup (Optional but Recommended)
Your Task model uses username as the foreign key to User—this field name is a bit misleading (it's actually linking to the entire User object, not just the username string). For better code clarity, you might want to rename it to user:
class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # Renamed from username titre = models.CharField(max_length=100) date = models.DateField() objectif = models.CharField(max_length=1000) theme = models.CharField(max_length=20)
If you make this change, update your filter line to tasks = Task.objects.filter(user=request.user) to match.
3. Template Check (No Extra Work Needed)
In your home.html template, you don't need additional filtering here—since the view already passed only the current user's tasks:
{% for task in tasks %} <div> <h3>{{ task.titre }}</h3> <p>{{ task.objectif }}</p> <!-- Add other task fields as needed --> </div> {% endfor %}
Why This Works
- The
@login_requireddecorator blocks access for unauthenticated users, preventing errors from missingrequest.userdata. request.usergives you the currently logged-in User object, so filtering tasks by this object ensures you only get entries linked to that user.- Switching to
render()instead ofrender_to_responseis modern Django practice—it automatically passes the request context to your template, so you can access{{ user }}directly if needed.
内容的提问来源于stack exchange,提问作者Nawal

