Home > Mobile >  How to update custom user's model fields using APIView update method
How to update custom user's model fields using APIView update method

Time:11-09

I am trying to code up a APIView's update method so I can change model fields in my custom AbstractUser model.

I read the documentation for APIViews and other examples, but most of them involved another OneToOne 'profile' model like in this example and or coding up the serializer which I don't think it's necessary for user model(correct me if I'm wrong)

I am unsure how to implement the same update method for a user model.

This is my custom user model. I am trying to update referred_count and tokens fields here from frontend

users/models.py

class User(AbstractUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    username = None
    first_name = models.CharField(max_length=100, default="unknown")
    last_name = models.CharField(max_length=100, default="unknown", blank=True)
    profile_pic = models.CharField(max_length=200, default="unknown")
    premium = models.BooleanField(default=False)
    referred_count = models.IntegerField(default=0)
    tokens = models.IntegerField(default=0)

    email = models.EmailField(unique=True, db_index=True)
    secret_key = models.CharField(max_length=255, default=get_random_secret_key)

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []

    objects = UserManager()

    class Meta:
        swappable = "AUTH_USER_MODEL"

users/api.py


class UpdateFields(ApiAuthMixin, ApiErrorsMixin, APIView):
    def update(self, request, *args, **kwargs):
        # update various user fields based on request.data
        # I am not sure what should go inside here.
        return request.user.update(request, *args, **kwargs)

I want to send something like the following from frontend which will pass through the UpdateFields APIView and 'patch' these user fields

{
  'tokens': 100,
  'referred_count': 12,
}

users/urls.py

urlpatterns = [
    path("me/", UserMeApi.as_view(), name="me"),
    path("update/", UpdatePremium.as_view(), name="update"),
]

CodePudding user response:

Try out this.

user = request.user
user.tokens = request.data.get('token')
user.referred_count = request.data.get('referred_count')
user.save()
  • Related