2017-03-07 45 views
0

我正在开发一个社交平台,目前正在编写用户帖子的类似功能。但是,我似乎无法使其工作。这是我的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. 

有没有人知道我失踪或做错了什么?

回答

2

当您期待Post实例时,您正在传递newlike.post一个数字(整数字段)。

这要高度重视工作:

from django.http.shortcuts import get_object_or_404 

def liking(request, post_id): 
    post = get_object_or_404(Post, id=post_id) 
    newlike = Like.objects.create(user=request.user, post=post) 
    return redirect(reverse('dashboard')) 

注1:更好地利用方便快捷get_object_or_404为了筹集404错误当特定帖子不存在。 注2:通过调用objects.create会自动保存到数据库并返回一个实例!

+0

为什么我在像模型回归“后”用户名?而不是内容? – Acework

+0

你的意思是像'print newlike.post'返回用户名?这实际上是在'Post'模型中用'__unicode __()'(如果使用python 2)或'__str __()'(用于python 3)方法定义的。当你在那个对象上执行'print'的时候,这个方法应该返回实际的字符串表示。 –

+0

不,我的意思是模型对象本身(如:post = models.ForeignKey(Post,null = True))。当我进入数据库时​​,我想看看谁(在这种情况下是用户对象)喜欢哪个帖子(帖子对象)。用户对象正确地返回谁的用户名,但后对象也返回一个用户名;来自帖子所有者的用户名,而不是帖子的内容本身。 – Acework

1

newlike.post应该是一个Post对象,而不是一个int。

你需要先找到ID后:

post = Post.objects.get(pk=post_id) 
newlike.post = post 

,或者,如果你不想做这个查询:

newlike.post_id = post_id 
+0

为什么我的'发布'在Like模型中返回用户名?而不是内容? – Acework