2021年3月27日星期六

How to implement password change in Django Rest Framework without repeating code (DRY principle)

I have a Django app that already has a web interface for changing passwords. It uses django.contrib.auth functions and django.views.generic.UpdateView. Here is the code:

class PasswordChangeView(LoginRequiredMixin, generic.UpdateView):      form_class = PasswordChangeForm      template_name = 'form.html'      input_value = 'update password'        def post(self, request, *args, **kwargs):          form = PasswordChangeForm(request.user, request.POST)          if form.is_valid():              user = form.save()              update_session_auth_hash(request, user)  # Important!              try:                  request.user.auth_token.delete()  # Important!              except (AttributeError, ObjectDoesNotExist):                  pass              messages.success(request, 'Your password was successfully updated!')              return redirect('/')          else:              messages.error(request, 'Please correct the error below.')        def get(self, request, **kwargs):          form = PasswordChangeForm(request.user)          return render(request, self.template_name, {'form': form, 'input_value': self.input_value})  

The above code works fine in the web interface. Now I want to implement REST API for changing passwords. I know that I can create APIView/viewset and serializer to do that (like the answers for this question), but it will violate DRY principle. What is the best way to implement the REST API interface for that given that there is already a fully-functional web interface?

https://stackoverflow.com/questions/66837700/how-to-implement-password-change-in-django-rest-framework-without-repeating-code March 28, 2021 at 09:40AM

没有评论:

发表评论