Hola, hallamos la solución a lo que andabas buscando, deslízate y la encontrarás a continuación.
Ejemplo 1: cómo crear un usuario y un perfil de usuario en django rest framework
classUserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer(required=True)classMeta:
model = User
fields =('url','email','profile','created',)defcreate(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
Ejemplo 2: cómo crear un usuario y un perfil de usuario en django rest framework
classUserManager(BaseUserManager):defcreate_user(self, email, password=None):ifnot 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
defcreate_superuser(self, email, password):
user = self.create_user(email, password=password)
user.is_admin =True
user.save()return user
classUser(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',)defis_staff(self):return self.is_admin
defhas_perm(self, perm, obj=None):returnTruedefhas_module_perms(self, app_label):returnTruedefget_short_name(self):return self.email
defget_full_name(self):return self.email
def__unicode__(self):return self.email
classProfile(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):returnu'Profile of user: 0'.format(self.user.email)defcreate_profile(sender, instance, created,**kwargs):if created:
Profile.objects.create(user=instance)
post_save.connect(create_profile, sender=User)defdelete_user(sender, instance=None,**kwargs):try:
instance.user
except User.DoesNotExist:passelse:
instance.user.delete()
post_delete.connect(delete_user, sender=Profile)
Recuerda que puedes difundir este enunciado si lograste el éxito.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)