django IntegrityError at /todo NOT NULL constraint failed:todo_todo.name我没有外键只有名称charfield

5cnsuln7  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(124)

models.py

from django.db import models

# Create your models here.
class ToDo(models.Model):
    name = models.CharField(max_length=200, default=" ")

字符串

views.py

from django.shortcuts import render, HttpResponse
from .models import ToDo

# Create your views here.
def home(request):
    # temp = ToDo.objects.all()
    # context = {'temp':temp}

    data = request.POST.get('name')
    print(data)
    context = {'data':data}

    return render(request, "todo/home.html", context)

def todo(request):
    # temp = ToDo.objects.all()
    # context = {'temp':temp}

    name = request.POST.get('name')

    todo = ToDo(name=name)
    todo.save()
    context = {'names' : todo}

    return render(request, "todo/todo.html", context)

todo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>

    <h1>TO DO LIST</h1>

    <form method="post" action="/todo">
        {% csrf_token %} 
        <label for="name"> </label>
        <input type="text" name="name" id="name">
        <br>
        <button type="submit">Add Task</button>
    </form>

    {% for x in names %}
    <h4>{{ x.name }}</h4>
    {% endfor %}
</body>
</html>


我已经尝试改变名称和ID的一切,在YouTube上,但没有解决方案,我不知道错误发生在错误页面中,它显示todo.save()有错误,但我不知道错误发生在请帮助:(

acruukt9

acruukt91#

该错误在消息“NOT NULL constraint failed:todo_todo.name”中有描述。

name = models.CharField(max_length=200, default=" ")

字符串
此字段不允许空值。
要解决此问题,您可以:
1.允许创建空值

name = models.CharField(max_length=200, null=True, blank=True, default=" ")


1.当name为null时,在视图中添加一些检查。

# Check if name is None or just whitespace
    if not name or name.isspace():
        # Handle this error: maybe redirect with an error message or render the form again
        context = {
            'error': 'Task name cannot be empty',
        }
        return render(request, "todo/todo.html", context)

相关问题