我正在使用Python3开发一个Django项目。当我尝试创建一个新任务时,出现了这个错误。
django.db.utils.IntegrityError: NOT NULL constraint failed: tasks_task.user_id
web应用程序工作正常,但当我试图创建一个新任务是错误发生时,我已经阅读了所有与问题相关的帖子,但没有找到解决方案。
我试着更新我的sqlite3,但是没有用。
"这是我的准则"
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from .forms import TaskForm
def home(request):
return render(request, 'home.html')
# Create your views here.
def signup(request):
if request.method == 'GET':
return render(request, 'signup.html', {
'form': UserCreationForm
})
else:
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.create_user(
username=request.POST['username'], password=request.POST['password1'])
user.save()
login(request, user)
return redirect('tasks')
except IntegrityError:
return render(request, 'signup.html', {
'form': UserCreationForm,
'error': 'Username already taken'
})
return render(request, 'signup.html', {
'form': UserCreationForm,
'error': 'Passwords did not match'
})
def tasks(request):
return render(request, 'tasks.html')
def create_task(request):
if request.method == 'GET':
return render(request, 'create_task.html', {
'form': TaskForm,
})
else:
try:
form = TaskForm(request.POST)
new_task = form.save(commit=False)
new_task.User = request.user
new_task.save()
return redirect('tasks')
except ValueError:
return render(request, 'create_task.html', {
'form': TaskForm,
'error': 'Bad data passed in. Try again.'
})
def signout(request):
logout(request)
return redirect('home')
def signin(request):
if request.method == 'GET':
return render(request, 'signin.html', {
'form': AuthenticationForm
})
else:
user = authenticate(
request, username=request.POST['username'], password=request.POST['password'])
if user is None:
return render(request, 'signin.html', {
'form': AuthenticationForm,
'error': 'Username and password did not match'
})
else:
login(request, user)
return redirect('tasks')
"这是我的models.py“
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Task(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
created = models.DateTimeField(auto_now_add=True)
datecompleted = models.DateTimeField(null=True, blank=True)
important = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title + ' | ' + str(self.user)
1条答案
按热度按时间yv5phkfx1#
在设置用户时,你似乎使用了错误的属性名。注意,所有Python属性都区分大小写:
但是
将其更改为
new_task.user
应该可以解决此问题。