I'm trying to create user specific access to my todolist website with Django

I'm getting an error when I make migrations in the command line. Please help

-models.py

from django.db import models
from django.contrib.auth.models import User

class ToDoList(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", null=True)
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name


class Item(models.Model):
    todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE)
    text = models.CharField(max_length=300)
    complete = models.BooleanField()

    def __str__(self):
        return self.text

When I tried to make migrations in the command line, I got this error cmd-pic

I used this command:

python manage.py makemigrations
python manage.py migrate

I used the tutorial from TechWithTim(link: https://www.youtube.com/watch?v=sm1mokevMWk&t=7589s) to do this project. It works fine for him but not for me.

Someone, please tell me where I went wrong.

Request is passed to views. response is what is returned from views, not the other way around(although can name request in different ways, but it's better to do it meaningfully).

ForeignKey creates a one-to-many relationship. The model in which this field is declared is considered secondary, and the model that is declared in this field is considered primary. Description here:

By using the primary model(ToDoList), you can get the data associated with it from the secondary model(Item). To do this, a special property (object) with the name secondary model_set is created in the primary model by default. In our case: item_set.

Note that the property is in lower case(the property is created with a small letter). You can also define it on your own using related_name (in this case, it will be the way you write it, without the _set prefix).

In the view, I first get data from the primary model based on the secondary(aaa.todolist that is, referring to the field of the secondary model, I get the name of the primary model, since the primary class returns the name. And then I get user through the name).

Then I use the primary to get the data of the secondary model (in the secondary model, I took only the first value). All received data is displayed on the page.

def create(request):
    aaa = Item.objects.get(id=1)
    name = aaa.todolist
    user = aaa.todolist.user

    bbb = ToDoList.objects.get(id=1)
    fff = bbb.item_set.all()[0]#takes the first element from the QuerySet .
    print(bbb.item_set.all())


    return HttpResponse(f"""
        <p>ferst name: {name}</p>
        <p>ferst user: {user}</p>
        <p>second todolist: {fff.todolist}</p>
        <p>second text: {fff.text}</p>
        <p>second complete: {fff.complete}</p>
    """)

urls.py

urlpatterns = [ 
    path("create/", create, name="create"),
]
Back to Top