如何修改Django待办事项应用代码实现用户专属独立任务列表
Hey there! The problem you're facing is totally common when getting started with Django authentication and models—right now your tasks aren't linked to any specific user, so every task is a global item that all users can see. Let's walk through the changes you need to make to give each user their own private task list.
Step 1: Update Your Model to Link Tasks to Users
First, we need to add a foreign key to your TodooModel that connects each task to a specific user. We'll use Django's built-in User model (or reference your custom user model if you've set one up, which is best practice):
from django.db import models from django.contrib.auth.models import User # Import Django's default User model # If you use a custom user model, replace the line above with: # from django.conf import settings # User = settings.AUTH_USER_MODEL class TodooModel(models.Model): fd = models.TextField() cr_dt = models.DateTimeField(auto_now_add=True) # Add this foreign key to link tasks to a user user = models.ForeignKey(User, on_delete=models.CASCADE)
on_delete=models.CASCADEmeans if a user is deleted, all their tasks will be deleted too. If you want a different behavior (like keeping tasks but unlinking them), you could useSET_NULLwithnull=True, blank=True.
After updating the model, run these commands to apply the changes to your database:
python manage.py makemigrations python manage.py migrate
Step 2: Modify the Create View to Assign Tasks to the Current User
Right now, when you create a task, you're not associating it with the logged-in user. Let's fix that in your create view:
def create(request): if request.user.is_authenticated: if request.method == "POST": fdk = request.POST.get("task") # Link the new task to the currently logged-in user data = TodooModel(fd=fdk, user=request.user) data.save() return render(request,"create.html",{"msg":"Added Succesfully"}) else: return render(request,"create.html") else: return redirect("user_login")
Step 3: Fix the Views Page to Show Only the Current User's Tasks
Your current views function uses TodooModel.objects.get() which will throw an error if there's more than one task (since get() expects exactly one result). Instead, we'll filter tasks to only those belonging to the logged-in user:
def views(request): if request.user.is_authenticated: # Fetch only tasks linked to the current user data = TodooModel.objects.filter(user=request.user) return render(request,"views.html",{"data":data}) else: return redirect("user_login")
- Note:
datais now a queryset (a collection of tasks), not a single object. In yourviews.htmltemplate, you'll need to loop through this queryset to display each task (see the template note below).
Step 4: Add a Safety Check to the Delete View
To prevent users from deleting tasks that don't belong to them, add a filter to the delete view:
def delete(request,id): if request.user.is_authenticated: try: # Only fetch the task if it belongs to the current user de = TodooModel.objects.get(id=id, user=request.user) de.delete() except TodooModel.DoesNotExist: # Handle cases where the task doesn't exist or isn't the user's pass return redirect("views") else: return redirect("user_login")
- The
try/exceptblock avoids errors if someone tries to delete a task that isn't theirs or doesn't exist.
Quick Template Note
In your views.html, make sure you're looping through the data queryset to display tasks. For example:
{% for task in data %} <div> <p>{{ task.fd }} - {{ task.cr_dt }}</p> <a href="{% url 'delete' task.id %}">Delete Task</a> </div> {% empty %} <p>No tasks added yet!</p> {% endfor %}
That's it! Now each user will only see and manage their own personal tasks. 🚀
内容的提问来源于stack exchange,提问作者Kaustubh Sawant

