Skip to content

Instantly share code, notes, and snippets.

Created October 11, 2018 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hwshim0810/3a624d6d7509d8ccb01342110fefb620 to your computer and use it in GitHub Desktop.
Save hwshim0810/3a624d6d7509d8ccb01342110fefb620 to your computer and use it in GitHub Desktop.
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):
serializer = self.get_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(
if not self.form_class.is_valid():
raise serializers.ValidationError(self.set_password_form.errors)
return attrs
def save(self):
self.user.has_password = True
# Forms
from django import forms
from django.contrib.auth import password_validation
class PasswordInitForm(forms.Form):
new_password = forms.CharField(
label=_("새로운 비밀번호", ''),
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"]
if commit:
return self.user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment