Django:如何链接到特定用户?

我正在尝试创建一个具有待办事项功能的网站!到目前为止,我已经对其进行了编程,因此它可以与一个用户完美配合。但是,当我用不同的用户登录时,我仍然可以查看我的待办事项列表,我不希望这样。


现在,如果我能让这个特定的功能对很多人有用,我会很高兴。所以这个人登录他的帐户,创建他自己的列表/我登录我的并创建我自己的列表。


我搜索了很多 youtube 教程和文章,但都没有帮助 :( 如果我能在这里解决这个问题,并且得到像您这样的编码专家的大量帮助,那就太棒了!


这是我与待办事项功能相关的代码


Views.py


def ToDo(request):

    todos = TodoList.objects.all()

    categories = Category.objects.all()

    if request.method == "POST":

        if "taskAdd" in request.POST:

            title = request.POST["description"]

            date = str(request.POST["date"])

            category = request.POST["category_select"]

            content = title + " -- " + date + " " + category

            Todo = TodoList(title=title, content=content, due_date=date, 

                            category=Category.objects.get(name=category))

            Todo.save()

            return redirect("/to_do")

        if "taskDelete" in request.POST:

            print(request.POST)

            checkedlist = request.POST.getlist('checkedbox')

            for todo_id in checkedlist:

                todo = TodoList.objects.get(id=int(todo_id))

                todo.delete()

    return render(request, 'Todolist.html', {"todos": todos, "categories":categories})

models.py


class TodoList(models.Model):

    title = models.CharField(max_length=250)

    content = models.TextField(blank=True)

    created = models.DateField(default=timezone.now().strftime("%Y-%m-%d"))

    due_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d"))

    category = models.ForeignKey(Category, on_delete=models.CASCADE)


    class Meta:

        ordering = ["-created"]


    def __str__(self):

        return self.title

全部.html


<div django-app="TaskManager">

<div class="container">

        <div class="content">

        <h2 style="text-align: center">Tasks are listed here!</h2>

        <p class="tagline">Jayden's To-Do system</p>

        <form action="" method="post">

        {% csrf_token %}

            <div class="inputContainer">

                <label for="category">What should I do??</label>


有人可以帮我让这个特定于用户吗?谢谢你!!


梦里花落0921
浏览 55回答 1
1回答

收到一只叮咚

首先,您的 TODO 模型需要关联到用户from django.conf import settingsclass TodoList(models.Model):&nbsp; &nbsp; user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)&nbsp; &nbsp; title = models.CharField(max_length=250)创建待办事项时,将其链接到用户def ToDo(request):&nbsp; &nbsp; ...&nbsp; &nbsp; Todo = TodoList(user=request.user, title=title, content=content, due_date=date,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; category=Category.objects.get(name=category))Todo.save()&nbsp; &nbsp; ...检索列表时,需要按用户过滤def ToDo(request):&nbsp; &nbsp; todos = ToDo.objects.filter(user=request.user)&nbsp; &nbsp; ...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python