简体   繁体   中英

I keep getting this error in Django, its called “local variable referenced before assignment”

I am making this to-do list website with Django, but I keep getting this error in my "create" function in views.py file. here's the code:

def create(response):
    if response.method == "POST":
        form = CreateNewList(response.POST)

        if form.is_valid():
            n = form.cleaned_data["name"]
            t = ToDoList(name=n)
            t.save()

        return HttpResponseRedirect("/%i" %t.id)

here's the error:

local variable 't' referenced before assignment

the class of the form is:

from django import forms


class CreateNewList(forms.Form):
    name = forms.CharField(label="name", max_length=200)
    check = forms.BooleanField()

the models are:

from django.db import models


class ToDoList(models.Model):
    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

I tried assigning the variable before the if statement. here's the code:

def create(response):
    if response.method == "POST":
        form = CreateNewList(response.POST)
        t = ToDoList.objects
        if form.is_valid():
            n = form.cleaned_data["name"]
            t.create(name=n)
            t.save()

        return HttpResponseRedirect("/%i" %t.id)

    else:
        form = CreateNewList()

    return render(response, "main/create.html", {"form":form})

If you want to create t object, you need to do it like:

...
t = ToDoList.objects.create(name=n)
t.save()

The problem is that t is defined in the if clause which might not always get satisfied and you end up with the error: local variable 't' referenced before assignment .

The fix could be to either create the t object before the if block with some default setting (None) or indent the return statement if that's what you wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM