0

I'm using the shell to make this happen:

serializer = UserSerializer(data={'first_name':'brody', 'username':'brodyboy'})
serializer.is_valid() // returns True
serializer.save() // I save it, assuming it should create a new User object.

When I check to see the User objects I've made:

User.objects.all() // <QuerySet [ ]>  -- returns nothing.

models.py:

class User(models.Model):
    first_name = models.CharField(max_length=20)      
    username = models.CharField(primary_key=True, max_length=20)
    age = models.IntegerField(default=19)

    def __str__(self):
        return self.first_name

Serializers.py

class UserSerializer(serializers.ModelSerializer):
   class Meta:
       model = User
       fields = ('first_name', 'username')

   def create(self, validated_data):
      return User.objects.create(**validated_data)

EDIT: not a duplicate so cash me ousside how bow dah

UPDATE: all I had to do was remove the create method. For some reason having that method prevented me from saving my User object to the database.

3
  • 2
    What does serializer.save() returns ? Commented Feb 5, 2017 at 22:00
  • Possible duplicate of django rest framework create user with password Commented Feb 5, 2017 at 22:00
  • @dnit13 it returns <User: brodyboy>, which I find strange because shouldn't that object be added to the User database, too? Commented Feb 5, 2017 at 22:23

1 Answer 1

1

I removed the create method and now I'm able to add Users to my database.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.