我跳进了这个错误。 我的Models.py文件是
class Post(models.Model):
user = models.ForeignKey(User,related_name='posts')
created_at = models.DateTimeField(auto_now=True)
message = models.TextField()
message_html = models.TextField(editable=False)
def __str__(self):
return self.message
def save(self,*args,**kwargs):
self.message_html = misaka.html(self.message)
super().save(*args,**kwargs)
def get_absolute_url(self):
return reverse('news:single',kwargs={'username':self.user.username,'pk':self.pk})
class Meta():
ordering = ['-created_at']
class Comment(models.Model):
post = models.ForeignKey('news.Post',related_name='comments')
aurthor = models.CharField(blank=False, max_length=100)
comment = models.TextField(blank=True)
created_date = models.DateTimeField(auto_now = True)
comment_html = models.TextField(editable = False)
def save(self,*args,**kwargs):
self.comment_html = misaka.html(self.comment)
super().save(*args,**kwargs)
def get_absolute_url(self):
return reverse('news:single',kwargs={'username':self.user.username,'pk':self.pk})
def __str__(self):
return self.comment
和我的Views.py文件是
class CommentCreateView(LoginRequiredMixin,generic.CreateView):
model = models.Comment
fields = ('comment',)
login_url = "/users/login"
def form_valid(self,form,*args,**kwargs):
self.object = form.save(commit = False)
self.object.aurthor = self.request.user
#self.object.post_id = self.kwargs['pk']
#print(self.request,self.kwargs['pk'])
self.object.save()
return super().form_valid(form)
我得到的错误是
IntegrityError at /posts/4/comment/
NOT NULL constraint failed: news_comment.post_id
Request Method: POST
Request URL: http://localhost:8000/posts/4/comment/
Django Version: 1.11.3
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: news_comment.post_id
Exception Location: C:\Users\Sahil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 328
Python Executable: C:\Users\Sahil\AppData\Local\Programs\Python\Python36-32\python.exe
Python Version: 3.6.0
Python Path:
['C:\\Users\\Sahil\\Documents\\GitHub\\news-for-good\\my_app',
'C:\\Users\\Sahil\\AppData\\Local\\Programs\\Python\\Python36-32\\python36.zip',
'C:\\Users\\Sahil\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs',
'C:\\Users\\Sahil\\AppData\\Local\\Programs\\Python\\Python36-32\\lib',
'C:\\Users\\Sahil\\AppData\\Local\\Programs\\Python\\Python36-32',
'C:\\Users\\Sahil\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages']
Server time: Tue, 25 Jul 2017 16:21:26 +0000
任何人都可以告诉错误是什么。
如果您需要其余代码This My Github Repo
提前致谢... 谢谢:)
答案 0 :(得分:0)
您忘记在视图中添加发布 foreignkey
字段保存。因为您未在评论模型中的帖子null=True
字段中定义foreignkey
。因此,在保存注释模型实例
def form_valid(self,form,*args,**kwargs):
self.object = form.save(commit = False)
self.object.aurthor = self.request.user
self.object.post = # Assign Post model instance
self.object.save()
return super().form_valid(form)