在尝试创建属于组和用户的帖子时运行以下代码时出现此错误:
from django.shortcuts import render, get_object_or_404
from groups.models import Group
from .models import Post
from django.utils import timezone
def create(request, group_id):
group = get_object_or_404(Group, pk= group_id)
if request.method == 'POST':
if request.POST['body'] and 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})
澄清一下,Groups是我创建的模型,而不是默认的Django模型,这就是我从groups.models导入它的原因。
这就是我的帖子模型:
from django.db import models
from django.contrib.auth.models import User
from groups.models import 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')
当我从groups.models文件导入它时,我不知道为什么错误在auth_group表中查找该组!任何帮助都会非常感激!
答案 0 :(得分:1)
在previous question中,Post.group
指向auth.Group
模型。现在您已将其更改为指向groups.Group
,您必须创建并运行迁移以更新数据库。