0

The task is to create an API endpoint “/updateUser” for updating the user information. The API request should take the User object as input and update the user.

My model is this:

class UserModel(AbstractUser):
    name = models.CharField(max_length=50)
    email = models.EmailField(max_length=50, unique=True, primary_key=True)
    phone = models.CharField(max_length=10, unique=True)
    gender = models.CharField(max_length=10, null=True)
    dob = models.DateField(null=True)
    username = models.CharField(max_length=50, unique=True)

    REQUIRED_FIELDS = []

Serializer is:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = ['id','name','username','email','phone','password']
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password !=None:
            instance.set_password(password)
        instance.save()
        return instance

url is:

from django.urls import path
from . views import RegisterView, UpdateUserView
urlpatterns = [
    path('register/', RegisterView.as_view()),
    path('updateUser/', UpdateUserView.as_view())
]

Now, how to create view for this which takes object as input and update it?!

1
  • please attach your view file too :) Commented Jan 23, 2022 at 6:56

1 Answer 1

1

I think to it this way, you have to override the update method to handle update of the user, it will look like this

 def update(self, instance, validated_data):
     """Your code to handle it"""
     return instance

Your view should inherit from UpdateAPIView (Here you can check the docs ) and then in your url file you should do it like this

urlpatterns = [
    path('register/', RegisterView.as_view()),
    path('updateUser/', UpdateUserView.as_view())
]

To do this without passing the id in the url path (as it is not secure by itself so you will have to write some code for permission) you have to override the get_object function like this:

def get_object(self):
  queryset = self.get_queryset()
  obj = get_object_or_404(queryset, user=self.request.user)
  return obj

By doing this it is secure.

Ps. """Your code to handle it""" is the code that you have to get the user and update its data based on what you want to do.

Some other way to do it is by creating some function based view, but this one works too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.