Django-rest-framework教程4中的AttributeError:身份验证

时间:2015-03-02 19:39:51

标签: python django django-rest-framework

我正在关注django-rest-framework教程,但我无法弄清楚这里发生了什么。

我创建了一个带有片段属性的UserSerializer类,我完成了所有导入

#--!-coding: utf-8
from rest_framework import serializers
from snippets.models import Snippet
from django.contrib.auth.models import User

class SnippetSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')

    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner')

class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())

    class Meta:
        model = User
        fields = ('id', 'username', 'snippets')

然后我创建了UserList和UserDetails视图:

class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

并且我已经非常遵循该教程,但是当我尝试访问其中一个用户端点时,我得到了一个AttributeError

AttributeError at /users/

'User' object has no attribute 'snippets'

我正在使用django 1.7.5和django-rest-framework 3.0.5

我不知道这个特定版本是否有问题。

编辑:

这是我的模特:

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank = True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
    owner = models.ForeignKey('auth.User')
    highlighted = models.TextField()

    class Meta:
        ordering = ('created',)

    def save(self, *args, **kwargs):
        """
        Usa o a biblioteca pygments para criar um representacao HTML com destaque do snippet
        """
        lexer = get_lexer_by_name(self.language)
        linenos = self.linenos and 'table' or False
        options = self.title and {'title': self.title} or {}
        formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)
        self.highlighted = highlight(self.code, lexer, formatter)
        super(Snippet, self).save(*args, **kwargs)

1 个答案:

答案 0 :(得分:9)

在您的代码段模型中,您需要向所有者字段添加相关名称。

owner = models.ForeignKey('auth.User', related_name='snippets')