how to create a User and User profile in django rest framework

class UserList(generics.ListCreateAPIView):
    permission_classes = (IsAuthenticatedOrWriteOnly,)
    serializer_class = UserSerializer

    def post(self, request, format=None):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

4.6
5
Awgiedawgie 440220 points

                                    class UserManager(BaseUserManager):
    def create_user(self, email, password=None):
        if not email:
            raise ValueError('User must have an email address')

        user = self.model(
            email = self.normalize_email(email),
        )
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password):
        user = self.create_user(email, password=password)
        user.is_admin = True
        user.save()
        return user


class User(AbstractBaseUser):
    objects = UserManager()
    email = models.EmailField(unique=True, db_index=True)
    created = models.DateTimeField('created', auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    is_active = models.BooleanField('active', default=True)
    is_admin = models.BooleanField('admin', default=False)

    USERNAME_FIELD = 'email'

    ordering = ('created',)

    def is_staff(self):
        return self.is_admin

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    def get_short_name(self):
        return self.email

    def get_full_name(self):
        return self.email

    def __unicode__(self):
        return self.email


class Profile(models.Model):
    GENDER = (
        ('M', 'Homme'),
        ('F', 'Femme'),
    )

    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    first_name = models.CharField(max_length=120, blank=False)
    last_name = models.CharField(max_length=120, blank=False)
    gender = models.CharField(max_length=1, choices=GENDER)
    zip_code = models.CharField(max_length=5, validators=[MinLengthValidator(5)], blank=False)

    def __unicode__(self):
        return u'Profile of user: {0}'.format(self.user.email)


def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
post_save.connect(create_profile, sender=User)


def delete_user(sender, instance=None, **kwargs):
    try:
        instance.user
    except User.DoesNotExist:
        pass
    else:
        instance.user.delete()
post_delete.connect(delete_user, sender=Profile)

4.6 (5 Votes)
0
4.14
7
Krish 100200 points

                                    class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer(required=True)
    class Meta:
        model = User
        fields = ('url', 'email', 'profile', 'created',)

    def create(self, validated_data):

        # create user 
        user = User.objects.create(
            url = validated_data['url'],
            email = validated_data['email'],
            # etc ...
        )

        profile_data = validated_data.pop('profile')
        # create profile
        profile = Profile.objects.create(
            user = user
            first_name = profile_data['first_name'],
            last_name = profile_data['last_name'],
            # etc...
        )

        return user

4.14 (7 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
django rest framework Building Custom User Model django user profile api django rest framework register user and update django rest framework user api user model django creation from rest django rest framework tutorial user registration and login user registration and login in django rest framework custom user model for django rest auth django rest api get user how to create user and login functionality using django rest framework user login django rest framework how to authenticate user in django rest framework create new user django rest framework Django rest Framework user registration and login example how to registyer the user with different fields in django rest franmework django rest framework add user custom user model django rest framework medium django rest framework set user as admin how to create custom user model in django rest framework custom user model login and registration in rest api django create profile with user django rest how to make custome user in django restframework django rest create profile with user user sign up django rest api Django Custom User model. Django rest framework project tutorial [4] user registration and login authentication django rest framework create a profile as user is created django rest django rest api create user creating a user profile using django rest framework update user profile django rest framework how to specify the current user to the user field in django rest create user in django rest framework how to create user id in django rest framework get user id in django rest framework user model django rest framework create user models in django rest framework django rest set user automatically django rest created by user django rest framework custom user model create user django api user accounts with django rest django rest framework user auth register user django rest framework easy django rest framework user registration and login django restframework manage user in RESTAPI how to register new user in django rest framework custom user model django rest framework djoser django automatically add current user to model rest framework django rest auth custom user model custom user model django rest framework django rest framework admin create user django rest framework register new user django rest framework create user as an admin Django rest framework user registration and login create user with django rest api register user django rest framework instanceof user profile default api for django user user and userprofile django rest framework django create user from view rest api django rest framework register user tutorial django rest framework custom user model registration and login how to get specific user django rest framework django rest framework custom user registration create a user using django rest framework django rest framework create profile user instance how to create user profile with user django API django rest api register user django api create user user profile django rest framework django rest framework user model django rest framework register user user registration django rest framework django rest framework user profile api rest registration profile django django rest-auth custom user model custom user model rest django user registration in django rest framework how to create user registration and login in django rest framework how to make different user in django rest framework api django rest get user django rest framework create with logged user django rest get user django rest framework user username instad of id django rest api for user registration django rest framework update user profile django rest framework create user command django rest create user django rest framework create user api django rest framework user registration example update user and user profile django rest framework django rest mange create user django rest framework create user django rest framework get user create_user django rest for profile create_user in django rest custom user django rest framework serializer customer profile user_profile_required django decorator how to create a User and User profile in django rest framework userprofile in user serializer Django rest framework api get user profile django rest framework api get my profile create a profile with user django django user profile example user profile api using django and django rest framework django rest framework profile django rest view profile user profile in django python django create user profile djangorest user and profile user and profile djangorest django rest user profile creating profile api djangorest how to create user profile with django-rest-auth how to create user profile with rest framework ModelSerializer fields user profile django rest framework user profile create profile with user model same instance rest-framework django rest and custom user profile django rest create user profile and related data
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source