我正在开发一个社交平台,目前正在编写用户帖子的类似功能。但是,我似乎无法使其工作。这是我的Models.py:像Django中的功能
class Post(models.Model):
user = models.ForeignKey(User)
posted = models.DateTimeField(auto_now_add=True)
content = models.CharField(max_length=150)
picturefile = models.ImageField(upload_to="post_content", blank=True)
class Like(models.Model):
user = models.ForeignKey(User, null=True)
post = models.ForeignKey(Post, null=True)
我通过我的网址为 'POST_ID' 通过帖子ID,然后在我的观点:
def liking(request, post_id):
newlike = Like.objects.create()
newlike.post = post_id
newlike.user = request.user
newlike.save()
return redirect(reverse('dashboard'))
但是,它返回以下错误:
Cannot assign "'47'": "Like.post" must be a "Post" instance.
有没有人知道我失踪或做错了什么?
为什么我在像模型回归“后”用户名?而不是内容? – Acework
你的意思是像'print newlike.post'返回用户名?这实际上是在'Post'模型中用'__unicode __()'(如果使用python 2)或'__str __()'(用于python 3)方法定义的。当你在那个对象上执行'print'的时候,这个方法应该返回实际的字符串表示。 –
不,我的意思是模型对象本身(如:post = models.ForeignKey(Post,null = True))。当我进入数据库时,我想看看谁(在这种情况下是用户对象)喜欢哪个帖子(帖子对象)。用户对象正确地返回谁的用户名,但后对象也返回一个用户名;来自帖子所有者的用户名,而不是帖子的内容本身。 – Acework