Tutorial error posting with username/password: "Owner field is required" But owner id is saved instead of username.

783 views
Skip to first unread message

Lewis

unread,
Jun 21, 2016, 4:42:31 PM6/21/16
to Django REST framework
Hey guys-
I'm following the tutorial and on step 4 I'm trying to post a snippet with a username/password like this example:
http -a tom:password123 POST http://127.0.0.1:8000/snippets/ code="print 789"

But I get this error:
 "owner": [
        "This field is required."
 ]

I'm able to login through the browsable API and post snippets for each user there.  But it's not working from the command line.

I also noticed that my owner values saved in the database are numeric id's (e.g. 1, 2) instead of my usernames like the tutorial shows. 

The tutorial shows this response:
{
    "id": 5,
    "owner": "tom",
    "title": "foo",
    "code": "print 789",
    "linenos": false,
    "language": "python",
    "style": "friendly"
}

But my snippets look like this, note the numeric "owner" value even though I'm logged in as user "joe":
    {
        "id": 1,
        "owner": 2,
        "title": "Test",
        "code": "Code for Test",
        "linenos": true,
        "language": "abap",
        "style": "algol",

    }

I'm new to python and django.  So I'm probably overlooking the obvious.  I haven't done any extra steps besides what the tutorial told me to do.  I tried finding an answer to this and found a post that suggested adding the following code:
def pre_save(self, obj):
    obj.owner = self.request.user

But that didn't make a difference.


Any thoughts on what step I might have messed up in the tutorial?
Thanks!

Lewis

unread,
Jun 21, 2016, 5:01:34 PM6/21/16
to Django REST framework
Problem solved!  I figured out my problem by watching this tutorial:

I accidentally defined my SnippetSerializer like this:
class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner')
        owner = serializers.ReadOnlyField(source='owner.username')

Instead of this (note the new location of the owner definition):
class SnippetSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')    
    
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner')

I hope this helps someone.

Vasco Lameiras

unread,
Oct 21, 2016, 6:24:20 AM10/21/16
to Django REST framework
Thanks! I was stuck at this step...

G Clovs

unread,
Nov 8, 2016, 8:53:02 AM11/8/16
to Django REST framework
I had the same Probleme!
Thanks for sharing.

Phil

unread,
Feb 3, 2017, 11:31:11 AM2/3/17
to Django REST framework
+1 another thank you for this!
Reply all
Reply to author
Forward
0 new messages