python – Django:’str’对象没有属性’user’

这是我的视图代码:

@login_required
def get_top(type):
    o = Work.objects.filter(types = "Fan Fiction").order_by("-date_updated")[:10]
    list = []
    for o in o:
        l.title = o.title
        l.href = "/" + o.id
        list.append(l)
    return l

@login_required
def main_home(request):
    fanfiction = get_top("ff")
    poetry = get_top("pw")
    originalwork = get_top("ow")
    return render_to_response("Main/main_home.html", {'STATIC_URL':STATIC_URL, "poetry":poetry, "fan":fanfiction, "original":originalwork})

这是模型的代码:

class Work(models.Model):
    title = models.CharField(max_length=30)
    summery = models.TextField()
    user = models.ForeignKey(User)
    date_published = models.DateField()
    date_updated = models.DateField()
    one_shot = models.BooleanField()
    completed = models.BooleanField()
    TYPES = (
        ('FF', 'Fan Fiction'),
        ('OF', 'Original Work'),
        ('PW', 'Poetry Work'),
        )
    types = models.CharField(max_length=2, choices=TYPES)
    fandom1 = models.ForeignKey(Book, blank = True, null= True, related_name='f_1')
    fandom2 = models.ForeignKey(Book, blank = True, null= True, related_name='f_2')
    def __unicode__(self):
    return self.title + '-' + self.user.email

这是错误:’str’对象在“get_top(”ff“)处没有属性’user’”

解决方法:

请删除get_top方法的@login_required装饰器.

这是尝试做的,@ logininquired尝试验证该用户是否已登录.这是试图在ff中找到一个用户对象实例,这是一个str因此是堆栈跟踪.通常@login_required从请求obj获取User,但是因为你没有在get_top中传递它,因此错误.

我的建议是你应该在views.py中维护一组方法,这些方法链接到urls.py中的API网址,其中一些可能需要@login_required.另一组方法是辅助方法(如get_top).这些不会暴露给外界(因此不需要@login_required).

如果必须在内部和外部公开get_top,那么get_top的第一个参数必须是请求对象,然后是其他参数.

上一篇:设计模式4-装饰器模式Decorator


下一篇:java – 用于IO的GoF Decorator模式的用例和示例