I'm following the django-rest-framework tutorial and I can't figure out what is happening here.
I've created a UserSerializer class with a snippets attribute and I did all the imports
#--!-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')
Then I've created the UserList and the UserDetails views:
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
and I've follow the tutorial pretty much, but when I try to access one of the users endpoints I got an AttributeError
AttributeError at /users/
'User' object has no attribute 'snippets'
I am using django 1.7.5 and django-rest-framework 3.0.5
I don't know if it is a problem for this specific version.
EDIT:
This is 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)
In your snippets model, you need to add a related name to your owner field.
owner = models.ForeignKey('auth.User', related_name='snippets')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With