gpt4 book ai didi

python - django1.9中发生IntegrityError

转载 作者:行者123 更新时间:2023-12-01 03:59:20 26 4
gpt4 key购买 nike

我是 django 1.9 的新手,我正在尝试制作一个应用程序,但我遇到了这个错误,我不知道如何修复它。这是我的错误和代码。错误:

IntegrityError at /blogapp//post/

NOT NULL constraint failed: blogapp_blog.user_id

在 models.py 中:

from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
class Blog(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=50)
content = models.CharField(max_length=99999)
date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title

在views.py中:

def post(request):
form = BlogText()

if request.method == 'POST':
form = BlogText(request.POST.copy())
if form.is_valid():
data = form.cleaned_data
title = data['title']
content = data['content']
if not Blog.objects.all().filter(title=title):
blog = Blog.objects.create(title=title,content=content,date=timezone.now())
return render(request,'blogapp/postok.html')
else:
return HttpResponse('The title is used')
else:
form = BlogText()
return render(request,'blogapp/post.html',{'form':form})

我需要在views.py中添加这个吗?:

if request.user.is_authenticated():

有人请帮帮我。我觉得我在这方面真的很糟糕。

最佳答案

您收到此错误是因为user_id 不能为空:

NOT NULL constraint failed: blogapp_blog.user_id

您还需要添加用户:

blog = Blog.objects.create(title=title, content=content,
date=timezone.now(), user=request.user)

另请确保只有登录用户才能使用login_required访问此 View 。装饰器:

@login_required
def post(request):
# your stuff here

关于python - django1.9中发生IntegrityError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36892329/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com