我正在通过实现跟随功能所必需的但是由于某种原因这不起作用
Error: TypeError at /follow/1/
在views.py中
def follow(request, pk):
following, created = Following.objects.get_or_create(
follow_from_id=request.user,
follow_to_id=pk)
return redirect('login')
models.py 中的
模板 class Following(models.Model):
follow_from = models.ForeignKey("auth.User",related_name='from_person')
follow_to = models.ForeignKey("auth.User", related_name='to_person')
date_follow = models.DateTimeField(auto_now=True)
def __unicode__(self):
return unicode(self.date_follow)
def __str__(self):
return self.date_follow
在urls.py中<a href="{% url 'follow' l.pk %}">
url(r'^follow/(?P<pk>\d+)/$', follow, name='follow'),
答案 0 :(得分:1)
follow_from
字段是用户模型的外键。在过滤器中,您将ID与用户实例进行比较。
您的过滤器follow_from
应该是:
follow_from=request.user
但是,如果要按id进行比较,请从用户实例中提取id
follow_from_id=request.user.id
答案 1 :(得分:0)
这是因为request.user对象是延迟加载的。将查找更改为:
def follow(request, pk):
following, created = Following.objects.get_or_create(
follow_from_id=request.user.id, <------------------------
follow_to_id=pk)
return redirect('login')