Значение по умолчанию в test.py равно
def test_register(self):
user = User.objects.create_user(first_name="test",last_name="test",username="test",password="testpassword",email="testemail@gmail.com")
register_form = UserRegisterForm(instance=user)
register_form_dict = UserRegisterFormSerializer(register_form).data
c = Client()
resp = c.post("/api/register/",register_form_dict)
self.assertEqual(resp.status_code,201)
Выходное значение равно
FAIL: test_register (api.tests.Test_Cases)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/user/project/api/tests.py", line 38, in test_register
self.assertEqual(resp.status_code,201)
AssertionError: 400 != 201
Значение по умолчанию в views.py равно
@api_view(['POST'])
def register_view(request):
new_user_form = UserRegisterForm(request.POST)
# Validate the form
if(new_user_form.is_valid()):
new_user = new_user_form.save()
content = {
'message':'You are successfully registered'
}
return Response(content, status=status.HTTP_201_CREATED)
content = {
'message':'Invalid Form'
}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
ModelForm и чистые методы:
class UserRegisterForm(ModelForm):
class Meta:
model = User
fields = ['username', 'password', 'email', 'first_name', 'last_name']
def clean_first_name(self):
first_name=self.cleaned_data.get('first_name')
if( not first_name.isalpha()):
raise forms.ValidationError("Not valid firstname")
return first_name
def clean_last_name(self):
last_name=self.cleaned_data.get('last_name')
if(not last_name.isalpha()):
raise forms.ValidationError("Not valid lastname")
return last_name
def clean_username(self):
username=self.cleaned_data.get('username')
try:
user = User.objects.get(username = username)
except User.DoesNotExist:
return username
raise forms.ValidationError("Username taken")
def clean_email(self):
email = self.cleaned_data.get("email")
is_valid = validate_email(str(email))
if(not is_valid):
raise forms.ValidationError("Not a valid email")
return email
def clean_password(self):
password = self.cleaned_data.get("password")
if( not (len(str(password)) >= 8)):
raise forms.ValidationError("Need longer password")
return password
Сериализатор:
class UserLoginFormSerializer(serializers.Serializer):
class Meta:
model = UserLoginForm
fields = '__all__'
Мой ожидаемый вывод - код состояния 201, но по какой-то причине new_user_form.is_valid () возвращает false, а register_view возвращает код состояния 400. Может кто-нибудь помочь, пожалуйста?