Skip to content

Instantly share code, notes, and snippets.

@hwshim0810 hwshim0810/views.py
Created Oct 11, 2018

Embed
What would you like to do?
Password init
# Views
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
class PasswordInitializeAPIView(CreateAPIView):
serializer_class = serializers.PasswordInitSerializer
def create(self, request, *args, **kwargs):
self.check_permissions(request)
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
return Response(status=status.HTTP_201_CREATED)
# Serializers
from rest_framework import serializers
class PasswordInitSerializer(serializers.Serializer):
new_password = serializers.CharField(max_length=128)
form_class = forms.PasswordInitForm
def __init__(self, *args, **kwargs):
self.request = self.context.get('request')
self.user = getattr(self.request, 'user', None)
super(PasswordInitSerializer, self).__init__(*args, **kwargs)
def validate(self, attrs):
self.set_password_form = self.form_class(
user=self.user,
data=attrs
)
if not self.form_class.is_valid():
raise serializers.ValidationError(self.set_password_form.errors)
return attrs
def save(self):
self.set_password_form.save()
self.user.has_password = True
self.user.save()
# Forms
from django import forms
from django.contrib.auth import password_validation
class PasswordInitForm(forms.Form):
new_password = forms.CharField(
label=_("새로운 비밀번호", ''),
widget=forms.PasswordInput,
strip=False,
help_text=password_validation.password_validators_help_text_html(),
)
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
def clean_new_password(self):
password = self.cleaned_data.get('new_password')
password_validation.validate_password(password, self.user)
return password
def save(self, commit=True):
password = self.cleaned_data["new_password"]
self.user.set_password(password)
if commit:
self.user.save()
return self.user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.