I am following the django-rest-framework tutorial and I cannot understand what is going on here.
I created a UserSerializer class with snippets attribute and I did all the import
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')
Then I created the UserList and UserDetails lists:
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
and I follow the tutorial very closely, but when I try to access one of the endpoints of the users, I got the AttributeError attribute
AttributeError at /users/
'User' object has no attribute 'snippets'
I am using django 1.7.5 and django-rest-framework 3.0.5
I do not know if this is a problem for this particular version.
EDIT:
These are my models:
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)