名称'get_object_or_404'未定义

时间:2019-11-24 08:27:47

标签: python django

我正在关注本教程:https://tutorial-extensions.djangogirls.org/en/homework_create_more_models/

我要添加到我创建的一个简单博客中,以便我可以添加评论

我错误:

name 'get_object_or_404' is not defined

通过views.py中的此方法

def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    # post = Post
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = CommentForm()
    return render(request, 'add_comment_to_post.html', {'form': form})

如您所见#的阴影线。这使我可以进入评论视图,但随后出现错误Cannot assign "<class 'blog.models.Post'>": "Comment.post" must be a "Post" instance.

这很有意义,但想指出这一点。

我认为这是数据库问题?

我的models.py

from django.db import models
from django.contrib.auth.models import User

STATUS = (
    (0,"Draft"),
    (1,"Publish")
)

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
    updated_on = models.DateTimeField(auto_now= True)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=0)

    class Meta:
        ordering = ['-created_on']

    def __str__(self):
        return self.title

class Comment(models.Model):
    comment = models.CharField(max_length=100)
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')

    def __str__(self):
        return self.comment

    class Meta:
        ordering = ['created_on']

教程中的所有内容都跟随着T。我什至经历了3次,然后重新复制并粘贴了所有内容,然后进行了迁移等。

我有什么要说的吗?

1 个答案:

答案 0 :(得分:2)

针对错误

name 'get_object_or_404' is not defined

我环顾了博客,他们似乎没有导入get_object_or_404。添加到代码顶部:

from django.shortcuts import get_object_or_404

Here是其中的文档。