Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to set current user to user field in Django Rest Framework

visit this website explained well:
  https://pyquestions.com/how-to-set-current-user-to-user-field-in-django-rest-framework
Comment

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

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)
Comment

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)
Comment

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

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
Comment

PREVIOUS NEXT
Code Example
Python :: python with braces 
Python :: pandas df tail 
Python :: production mode flask 
Python :: spliting the text to lines and keep the deliminaters python 
Python :: python run linux command and get output 
Python :: using shebang python 
Python :: pandas print groupby 
Python :: pip vs conda 
Python :: closures in python 
Python :: Python | Creating a Pandas dataframe column based on a given condition 
Python :: dataframe.fillna 
Python :: app.py 
Python :: numpy array [-1] 
Python :: Python List clear() 
Python :: python isdigit 
Python :: py quick sort 
Python :: fix the size of a deque python 
Python :: truthy falsy python 
Python :: discord python application bot 
Python :: python catch print 
Python :: programação funcional python - lambda 
Python :: longest common prefix 
Python :: removing stop words from the text 
Python :: pandas filter columns with IN 
Python :: gui button in tkinter color 
Python :: 3d data visualization python 
Python :: python print every row of dataframe 
Python :: cosine similarity numpy 
Python :: how to define a dictionary in python 
Python :: Set .difference() Operation in python3 
ADD CONTENT
Topic
Content
Source link
Name
2+8 =