/ posts / create / 15 /中的ValueError:无法分配“<group:group =”“2 =”“>”:“Post.group”必须是“Group”实例

时间:2018-04-26 12:23:51

标签: django django-models django-forms

我正在为帖子编写创建方法,该方法属于一个组和一个用户。我一直收到这个错误,虽然这是在文档和我看过的所有其他来源中完成的。这是相关文件:

models.py

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


class Post(models.Model):
    title = models.CharField(max_length=255, unique=True)
    body = models.TextField()
    likes_total = models.IntegerField(default=0)
    pub_date = models.DateTimeField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)


def __str__(self):
    return self.name

def summary(self):
    # return the 1st 100 chars
    return self.body[:100]

def pub_date_pretty(self):
    # strftime is how to break down time
    return self.pub_date.strftime('%b %e %Y')

posts.urls.py

from . import views
from django.urls import path


app_name = 'posts'

urlpatterns = [
    path('create/<int:group_id>/', views.create, name='create'),
]

posts.views.py

def create(request, group_id):
    group = get_object_or_404(Group, pk= group_id)
    if request.method == 'POST':
        if request.POST['body']:
            post = Post()
            post.title = request.POST['title']
            post.body = request.POST['body']
            post.pub_date = timezone.datetime.now()
            post.author = request.user
            post.group = group
            post.save()
            return redirect('/groups/' + str(group_id))

        else:
            return render(request, 'groups/detail.html', {'group':group})

    else:
        return render(request, 'groups/detail.html', {'group':group})

当我将组保存到帖子(post.group = group)时会抛出错误,尽管这是我学到的方法。希望有人能解决这个问题。谢谢!

1 个答案:

答案 0 :(得分:4)

您似乎混淆了两种不同的Group模型。在您的模型中,您有:

from django.contrib.auth.models import User, Group

并且在您看来,您有:

from groups.models import Group 

这些是完全不同的类,这就是为什么您收到错误消息,告诉您不能将groups.models.Group分配给应该是auth.models.Group的内容。

我不确定你打算做什么,但你需要在两个地方使用同一个班级。