Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError during Django-rest-framework tutorial 4: authentication

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)
like image 402
Fernando Freitas Alves Avatar asked Mar 02 '15 19:03

Fernando Freitas Alves


1 Answers

In your snippets model, you need to add a related name to your owner field.

owner = models.ForeignKey('auth.User', related_name='snippets')
like image 190
Alexander Avatar answered Sep 21 '22 11:09

Alexander