[英]django.db.utils.IntegrityError: NOT NULL constraint failed: user.id
I don't know why the error is caused even though I designated the author.即使我指定了作者,我也不知道为什么会导致错误。 I'd appreciate your help.我会很感激你的帮助。
model & form model & 表格
class SuperTitle(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='debate_author')
super_title = models.CharField(max_length=100)
liker = models.ManyToManyField(User, related_name='debate_liker')
def __str__(self):
return self.super_title
class SuptitForm(forms.ModelForm):
class Meta:
model = SuperTitle
fields = ['super_title']
views.py视图.py
def create(request):
...
dic = {'super_title' : request.POST.get('sup_title')}
sup_form = SuptitForm(dic)
if sup_form.is_valid():
sup_form.author = request.user
sup_form.super_title = ...
sup_form.save()
...
return IntegrityError at /polls/debate/create/ NOT NULL constraint failed: polls_supertitle.author_id在 /polls/debate/create/ NOT NULL 约束返回 IntegrityError 失败:polls_supertitle.author_id
You get this error becouse you want to save form(create new SuperTitle objetd in database) without author.您会收到此错误,因为您想在没有作者的情况下保存表单(在数据库中创建新的 SuperTitle 对象)。 You need to pass author objectd or id somehow to form.您需要以某种方式传递作者反对或 id 来形成。 If the request.user is author i recommend form:如果 request.user 是作者,我推荐表格:
class SuptitForm(forms.ModelForm):
class Meta:
model = SuperTitle
fields = ['super_title', 'author']
widgets = {'author': forms.HiddenInput()}
and in view:并认为:
def create(request):
if request.method == 'POST':
sup_form = SuptitForm(request.POST)
if sup_form.is_valid():
sup_form.save()
else:
sup_form = SuptitForm(initial={'author': request.user}
...
Probably you don't have authenticated user so that request.user
is returning None.可能您没有经过身份验证的用户,因此request.user
返回无。
Make use of login_required
decorator so that only the authenticated user can access this function.使用login_required
装饰器,以便只有经过身份验证的用户才能访问此 function。
from django.contrib.auth.decorators import login_required
@login_required
def create(request):
........
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.