Reputation: 928
At first I also saw this Post, but this doesn't work for me.
I have a Django Rest Framework Project. If I create a user through django directly I get errors like:
But if I have a normal HTTP POST Request I get a normal 200 Response:
{"email": "[email protected]", "response": "successfully registered new user.", "token": "3618d0c362dd66bbb093e1234b72901f9d74a905", "username": "haha"}
What is the problem? I also tried to build a custom validation for the password, but this isn't really what I want, because it is a great Django feature.
api/serializers.py
class RegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['email', 'username', 'password', 'password2',]
def save(self):
account = Account(
email = self.validated_data['email'],
username = self.validated_data['username'],
)
password = self.validated_data['password']
password2 = self.validated_data['password2']
if password != password2:
raise serializers.ValidationError({'password': 'Passwords must match.'})
account.set_password(password)
account.save()
api/views.py
@api_view(['POST', ])
def registration_view(request):
if request.method == 'POST':
serializer = RegistrationSerializer(data=request.data)
data = {}
if serializer.is_valid():
account = serializer.save()
data['response'] = 'successfully registered new user.'
data['email'] = account.email
data['username'] = account.username
token = Token.objects.get(user = account).key
data['token'] = token
else:
data = serializer.errors
print(data)
return Response(data)
Maybe you had the same problem?
Upvotes: 1
Views: 602
Reputation: 91
The problem is, that you don't have a password validation. So it's very simple:
api/serializers.py
from django.contrib.auth.password_validation import validate_password
...
class RegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['email', 'username', 'password', 'password2',]
def save(self):
account = Account(
email = self.validated_data['email'],
username = self.validated_data['username'],
)
password = self.validated_data['password']
password2 = self.validated_data['password2']
if password != password2:
raise serializers.ValidationError({'password': 'Passwords must match.'})
-> validate_password(password)
account.set_password(password)
account.save()
Upvotes: 2