Django Rest Framework - Check Password to Validate Form











up vote
0
down vote

favorite












I'm trying to validate a form through DRF, but it would require the user to enter their password for confirmation. I can't seem to get it to work. Here is my current View and Serializer. Its for a 'change email' form, two fields required, the email and user password. It's for a seperate email model. The serializer:



class UpdateEmailAddressSerializer(serializers.ModelSerializer):

class Meta:
model = EmailAddress
fields = ('email',)


And the APIView:



class UpdateEmailAPI(APIView):

permission_classes = (IsAuthenticated,)
serializer_class = UpdateEmailAddressSerializer

def post(self, request, user, format=None):
user = User.objects.get(username=user)
serializer = UpdateEmailAddressSerializer(data=request.data, instance=user)
if serializer.is_valid():

## logic to check and send email

serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)

else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


I'm not sure where to place the password or what to do with it. Its from the User model itself. When I attempted to add password to the fields in the UpdateEmail serializer it ended up updating the User password with plain text and making that user object unable to use that password.



I just want to check the password of the user for confirmation of this form. Is there an obvious way to do this?



EDIT



When I attempt to bring 'password' into the serializer, an error tells "Field name password is not valid for model EmailAddress." So when I attempt to bring it in e.g.



password = serializers.CharField(required=True)


or try:



## UserPasswordSerializer 
class UserPasswordSerializer(serializers.ModelSerializer):

class Meta:
model = User
fields = (
'password',
)

## In UpdateEmailAddressSerializer
password = UserPasswordSerializer()


I get this error when submitting the form on DRF:




Got AttributeError when attempting to get a value for field
password on serializer UpdateEmailAddressSerializer. The
serializer field might be named incorrectly and not match any
attribute or key on the EmailAddress instance. Original exception
text was: 'EmailAddress' object has no attribute 'password'




So it seems to be telling me password isn't part of EmailAddress model which is correct. But I cant figure out how to simply check the password alongside the form post without making it part of EmailAddress.










share|improve this question
























  • Possible duplicate of integrate django password validators with django rest framework validate_password
    – nara_l
    Nov 11 at 2:56










  • I've checked that answer already but its for registration and only for the user model. I can't get the password field from the user model to function on a completely separate model.
    – user3752958
    Nov 11 at 3:17















up vote
0
down vote

favorite












I'm trying to validate a form through DRF, but it would require the user to enter their password for confirmation. I can't seem to get it to work. Here is my current View and Serializer. Its for a 'change email' form, two fields required, the email and user password. It's for a seperate email model. The serializer:



class UpdateEmailAddressSerializer(serializers.ModelSerializer):

class Meta:
model = EmailAddress
fields = ('email',)


And the APIView:



class UpdateEmailAPI(APIView):

permission_classes = (IsAuthenticated,)
serializer_class = UpdateEmailAddressSerializer

def post(self, request, user, format=None):
user = User.objects.get(username=user)
serializer = UpdateEmailAddressSerializer(data=request.data, instance=user)
if serializer.is_valid():

## logic to check and send email

serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)

else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


I'm not sure where to place the password or what to do with it. Its from the User model itself. When I attempted to add password to the fields in the UpdateEmail serializer it ended up updating the User password with plain text and making that user object unable to use that password.



I just want to check the password of the user for confirmation of this form. Is there an obvious way to do this?



EDIT



When I attempt to bring 'password' into the serializer, an error tells "Field name password is not valid for model EmailAddress." So when I attempt to bring it in e.g.



password = serializers.CharField(required=True)


or try:



## UserPasswordSerializer 
class UserPasswordSerializer(serializers.ModelSerializer):

class Meta:
model = User
fields = (
'password',
)

## In UpdateEmailAddressSerializer
password = UserPasswordSerializer()


I get this error when submitting the form on DRF:




Got AttributeError when attempting to get a value for field
password on serializer UpdateEmailAddressSerializer. The
serializer field might be named incorrectly and not match any
attribute or key on the EmailAddress instance. Original exception
text was: 'EmailAddress' object has no attribute 'password'




So it seems to be telling me password isn't part of EmailAddress model which is correct. But I cant figure out how to simply check the password alongside the form post without making it part of EmailAddress.










share|improve this question
























  • Possible duplicate of integrate django password validators with django rest framework validate_password
    – nara_l
    Nov 11 at 2:56










  • I've checked that answer already but its for registration and only for the user model. I can't get the password field from the user model to function on a completely separate model.
    – user3752958
    Nov 11 at 3:17













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm trying to validate a form through DRF, but it would require the user to enter their password for confirmation. I can't seem to get it to work. Here is my current View and Serializer. Its for a 'change email' form, two fields required, the email and user password. It's for a seperate email model. The serializer:



class UpdateEmailAddressSerializer(serializers.ModelSerializer):

class Meta:
model = EmailAddress
fields = ('email',)


And the APIView:



class UpdateEmailAPI(APIView):

permission_classes = (IsAuthenticated,)
serializer_class = UpdateEmailAddressSerializer

def post(self, request, user, format=None):
user = User.objects.get(username=user)
serializer = UpdateEmailAddressSerializer(data=request.data, instance=user)
if serializer.is_valid():

## logic to check and send email

serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)

else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


I'm not sure where to place the password or what to do with it. Its from the User model itself. When I attempted to add password to the fields in the UpdateEmail serializer it ended up updating the User password with plain text and making that user object unable to use that password.



I just want to check the password of the user for confirmation of this form. Is there an obvious way to do this?



EDIT



When I attempt to bring 'password' into the serializer, an error tells "Field name password is not valid for model EmailAddress." So when I attempt to bring it in e.g.



password = serializers.CharField(required=True)


or try:



## UserPasswordSerializer 
class UserPasswordSerializer(serializers.ModelSerializer):

class Meta:
model = User
fields = (
'password',
)

## In UpdateEmailAddressSerializer
password = UserPasswordSerializer()


I get this error when submitting the form on DRF:




Got AttributeError when attempting to get a value for field
password on serializer UpdateEmailAddressSerializer. The
serializer field might be named incorrectly and not match any
attribute or key on the EmailAddress instance. Original exception
text was: 'EmailAddress' object has no attribute 'password'




So it seems to be telling me password isn't part of EmailAddress model which is correct. But I cant figure out how to simply check the password alongside the form post without making it part of EmailAddress.










share|improve this question















I'm trying to validate a form through DRF, but it would require the user to enter their password for confirmation. I can't seem to get it to work. Here is my current View and Serializer. Its for a 'change email' form, two fields required, the email and user password. It's for a seperate email model. The serializer:



class UpdateEmailAddressSerializer(serializers.ModelSerializer):

class Meta:
model = EmailAddress
fields = ('email',)


And the APIView:



class UpdateEmailAPI(APIView):

permission_classes = (IsAuthenticated,)
serializer_class = UpdateEmailAddressSerializer

def post(self, request, user, format=None):
user = User.objects.get(username=user)
serializer = UpdateEmailAddressSerializer(data=request.data, instance=user)
if serializer.is_valid():

## logic to check and send email

serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)

else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


I'm not sure where to place the password or what to do with it. Its from the User model itself. When I attempted to add password to the fields in the UpdateEmail serializer it ended up updating the User password with plain text and making that user object unable to use that password.



I just want to check the password of the user for confirmation of this form. Is there an obvious way to do this?



EDIT



When I attempt to bring 'password' into the serializer, an error tells "Field name password is not valid for model EmailAddress." So when I attempt to bring it in e.g.



password = serializers.CharField(required=True)


or try:



## UserPasswordSerializer 
class UserPasswordSerializer(serializers.ModelSerializer):

class Meta:
model = User
fields = (
'password',
)

## In UpdateEmailAddressSerializer
password = UserPasswordSerializer()


I get this error when submitting the form on DRF:




Got AttributeError when attempting to get a value for field
password on serializer UpdateEmailAddressSerializer. The
serializer field might be named incorrectly and not match any
attribute or key on the EmailAddress instance. Original exception
text was: 'EmailAddress' object has no attribute 'password'




So it seems to be telling me password isn't part of EmailAddress model which is correct. But I cant figure out how to simply check the password alongside the form post without making it part of EmailAddress.







django django-rest-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 14:23

























asked Nov 11 at 2:42









user3752958

3215




3215












  • Possible duplicate of integrate django password validators with django rest framework validate_password
    – nara_l
    Nov 11 at 2:56










  • I've checked that answer already but its for registration and only for the user model. I can't get the password field from the user model to function on a completely separate model.
    – user3752958
    Nov 11 at 3:17


















  • Possible duplicate of integrate django password validators with django rest framework validate_password
    – nara_l
    Nov 11 at 2:56










  • I've checked that answer already but its for registration and only for the user model. I can't get the password field from the user model to function on a completely separate model.
    – user3752958
    Nov 11 at 3:17
















Possible duplicate of integrate django password validators with django rest framework validate_password
– nara_l
Nov 11 at 2:56




Possible duplicate of integrate django password validators with django rest framework validate_password
– nara_l
Nov 11 at 2:56












I've checked that answer already but its for registration and only for the user model. I can't get the password field from the user model to function on a completely separate model.
– user3752958
Nov 11 at 3:17




I've checked that answer already but its for registration and only for the user model. I can't get the password field from the user model to function on a completely separate model.
– user3752958
Nov 11 at 3:17












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










I think you can try like this:



class UpdateEmailAddressSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = EmailAddress
fields = ('email', 'password',)

def create(self, validated_data):
validated_data.pop('password', None)
return super(UpdateEmailAddressSerializer, self).create(validated_data)

def update(self, instance, validated_data):
if instance.check_password(validated_data.get('password')):
instance.email = validated_data.get('email', instance.email)
# else throw validation error
return instance





share|improve this answer























  • Thanks, I've update my question.
    – user3752958
    Nov 11 at 14:24












  • I thought password was part of your model. Anyways, updated my answer @user3752958
    – ruddra
    Nov 11 at 15:21






  • 1




    Your answer set me in the right direction. It works once you add the check_password method to create, (update isn't called in this instance). Or better to a validate_password() method. Specifically grabbing the user object from initial data and then checking user.check_password(value). But removing password from create is what was needed. Thanks.
    – user3752958
    Nov 12 at 15:03











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245393%2fdjango-rest-framework-check-password-to-validate-form%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote



accepted










I think you can try like this:



class UpdateEmailAddressSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = EmailAddress
fields = ('email', 'password',)

def create(self, validated_data):
validated_data.pop('password', None)
return super(UpdateEmailAddressSerializer, self).create(validated_data)

def update(self, instance, validated_data):
if instance.check_password(validated_data.get('password')):
instance.email = validated_data.get('email', instance.email)
# else throw validation error
return instance





share|improve this answer























  • Thanks, I've update my question.
    – user3752958
    Nov 11 at 14:24












  • I thought password was part of your model. Anyways, updated my answer @user3752958
    – ruddra
    Nov 11 at 15:21






  • 1




    Your answer set me in the right direction. It works once you add the check_password method to create, (update isn't called in this instance). Or better to a validate_password() method. Specifically grabbing the user object from initial data and then checking user.check_password(value). But removing password from create is what was needed. Thanks.
    – user3752958
    Nov 12 at 15:03















up vote
1
down vote



accepted










I think you can try like this:



class UpdateEmailAddressSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = EmailAddress
fields = ('email', 'password',)

def create(self, validated_data):
validated_data.pop('password', None)
return super(UpdateEmailAddressSerializer, self).create(validated_data)

def update(self, instance, validated_data):
if instance.check_password(validated_data.get('password')):
instance.email = validated_data.get('email', instance.email)
# else throw validation error
return instance





share|improve this answer























  • Thanks, I've update my question.
    – user3752958
    Nov 11 at 14:24












  • I thought password was part of your model. Anyways, updated my answer @user3752958
    – ruddra
    Nov 11 at 15:21






  • 1




    Your answer set me in the right direction. It works once you add the check_password method to create, (update isn't called in this instance). Or better to a validate_password() method. Specifically grabbing the user object from initial data and then checking user.check_password(value). But removing password from create is what was needed. Thanks.
    – user3752958
    Nov 12 at 15:03













up vote
1
down vote



accepted







up vote
1
down vote



accepted






I think you can try like this:



class UpdateEmailAddressSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = EmailAddress
fields = ('email', 'password',)

def create(self, validated_data):
validated_data.pop('password', None)
return super(UpdateEmailAddressSerializer, self).create(validated_data)

def update(self, instance, validated_data):
if instance.check_password(validated_data.get('password')):
instance.email = validated_data.get('email', instance.email)
# else throw validation error
return instance





share|improve this answer














I think you can try like this:



class UpdateEmailAddressSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = EmailAddress
fields = ('email', 'password',)

def create(self, validated_data):
validated_data.pop('password', None)
return super(UpdateEmailAddressSerializer, self).create(validated_data)

def update(self, instance, validated_data):
if instance.check_password(validated_data.get('password')):
instance.email = validated_data.get('email', instance.email)
# else throw validation error
return instance






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 11 at 15:20

























answered Nov 11 at 4:37









ruddra

9,63332547




9,63332547












  • Thanks, I've update my question.
    – user3752958
    Nov 11 at 14:24












  • I thought password was part of your model. Anyways, updated my answer @user3752958
    – ruddra
    Nov 11 at 15:21






  • 1




    Your answer set me in the right direction. It works once you add the check_password method to create, (update isn't called in this instance). Or better to a validate_password() method. Specifically grabbing the user object from initial data and then checking user.check_password(value). But removing password from create is what was needed. Thanks.
    – user3752958
    Nov 12 at 15:03


















  • Thanks, I've update my question.
    – user3752958
    Nov 11 at 14:24












  • I thought password was part of your model. Anyways, updated my answer @user3752958
    – ruddra
    Nov 11 at 15:21






  • 1




    Your answer set me in the right direction. It works once you add the check_password method to create, (update isn't called in this instance). Or better to a validate_password() method. Specifically grabbing the user object from initial data and then checking user.check_password(value). But removing password from create is what was needed. Thanks.
    – user3752958
    Nov 12 at 15:03
















Thanks, I've update my question.
– user3752958
Nov 11 at 14:24






Thanks, I've update my question.
– user3752958
Nov 11 at 14:24














I thought password was part of your model. Anyways, updated my answer @user3752958
– ruddra
Nov 11 at 15:21




I thought password was part of your model. Anyways, updated my answer @user3752958
– ruddra
Nov 11 at 15:21




1




1




Your answer set me in the right direction. It works once you add the check_password method to create, (update isn't called in this instance). Or better to a validate_password() method. Specifically grabbing the user object from initial data and then checking user.check_password(value). But removing password from create is what was needed. Thanks.
– user3752958
Nov 12 at 15:03




Your answer set me in the right direction. It works once you add the check_password method to create, (update isn't called in this instance). Or better to a validate_password() method. Specifically grabbing the user object from initial data and then checking user.check_password(value). But removing password from create is what was needed. Thanks.
– user3752958
Nov 12 at 15:03


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245393%2fdjango-rest-framework-check-password-to-validate-form%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Florida Star v. B. J. F.

Danny Elfman

Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues