2017-08-27 121 views
0

我試圖將評論表單提交給相應的博客。當我這樣做時,我收到錯誤「NOT NULL約束失敗:blog_comment.posts_id」。django - NOT NULL約束失敗:blog_comment.posts_id

views.py

def add_comment(request, slug): 
post = get_object_or_404(Post, slug=slug) 
if request.method == 'POST': 
    form = CommentForm(request.POST) 
    if form.is_valid(): 
     comment = form.save(commit=False) 
     comment.post = post 
     comment.save() 
     return redirect('blog:post_detail', slug=post.slug) 
else: 
    form = CommentForm() 
template = "blog/post/add_comment.html" 
context = {'form': form} 
return render(request, template, context) 

forms.py

class CommentForm(forms.ModelForm): 
class Meta: 
    model = Comment 
    fields = ('user', 'email', 'title', 'body',) 

models.py

class Post(models.Model): 
STATUS_CHOISES = (

    ('draft', 'Draft'), 
    ('published', 'Published'), 

    ) 
category = models.ForeignKey(Category) 
title = models.CharField(max_length=250) 
slug = models.SlugField(max_length=250, unique=True) 
content = models.TextField() 
seo_title = models.CharField(max_length=250) 
seo_description = models.CharField(max_length=160) 
author = models.ForeignKey(User, related_name='blog_posts', default=settings.AUTH_USER_MODEL) 
published = models.DateTimeField(default=timezone.now) 
created = models.DateTimeField(auto_now_add=True) 
updated = models.DateTimeField(auto_now=True) 
status = models.CharField(max_length=9, choices=STATUS_CHOISES, default='draft') 

def get_absolute_url(self): 
    return reverse('blog:post_detail', args=[self.slug]) 


def __str__(self): 
    return self.title 



class Comment(models.Model): 
    posts = models.ForeignKey(Post, related_name="comments") 
    user = models.CharField(max_length=250) 
    email = models.EmailField() 
    title = models.CharField(max_length=250) 
    body = models.TextField() 
    created = models.DateTimeField(auto_now_add=True) 
    approved = models.BooleanField(default=False) 

    def approved(self): 
     self.approved = True 
     self.save() 

    def __str__(self): 
     return self.title 

什麼是錯我的代碼?

從我所瞭解的某處/某種程度上來說,評論並沒有發送到正確的博客文章,因爲如果我將我的表單設置爲帖子欄並手動選擇它,它就可以工作。但理想情況下,我希望它會自動發送到相應的博客。

回答

1

Comment模型ForeignKeyPost的型號被命名爲posts不是post,因此你需要做的:

if form.is_valid(): 
    comment = form.save(commit=False) 
    comment.posts = post 
    comment.save() 

它更有意義,只是重命名ForeignKey的,並將其命名爲post

class Comment(models.Model): 
    post = models.ForeignKey(Post, related_name="comments") 
+0

你是對的,我正在重新命名測試的東西,看看他們究竟做了什麼(我正在跟隨一個教程,我暫停試圖瞭解將要發生的事情),我忘記重新命名了。如果沒有你的幫助,我不會注意到它!非常感謝!!它現在有效:D – dmandres

相關問題