Home > Blockchain >  Django issue saving data to database
Django issue saving data to database

Time:12-01

username is saving but information such as first_name, email and etc are not.

`from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from rest_framework import serializers


class RegisterSerializer(serializers.ModelSerializer):

    email = serializers.CharField(required=True)
    first_name = serializers.CharField(max_length=50, required=True)
    last_name = serializers.CharField(max_length=50, required=True)
    password = serializers.CharField(
        write_only=True, required=True, validators=[validate_password])
    password2 = serializers.CharField(write_only=True, required=True)
    is_admin = serializers.BooleanField(default=False)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email',
                  'password', 'password2', 'is_admin')

    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError(
                {"password": "Password fields didn't match."})

        return attrs

    def create(self, validated_data):
        user = User.objects.create(
            username=validated_data['username']
        )

        user.set_password(validated_data['password'])
        user.save()

        return user`

i have searched online for hours, but have not managed to make much progress. if someone could elaborate on my issue and explain what I have done wrong that would be greatly appreciated

CodePudding user response:

Add all the fields that you need to create that exist in model inside create method

user = User.objects.create(
    username=validated_data['username'],   
    first_name =validated_data['first_name'],
    last_name =validated_data['last_name'],  
    # Add other fields here
)

CodePudding user response:

You should also send other validated data's to creation line:

def create(self, validated_data):
        user = User.objects.create(
            username=validated_data['username'],
            first_name=validated_data['first_name'], # <-- add here to all necessary parameters like this
        )

        user.set_password(validated_data['password'])
        user.save()
  • Related