Search code examples
pythondjangodjango-modelsdjango-viewsdjango-forms

Django ModelForm as a layer of data validation


I have an authorization form, and I get an error - "already have a user with this email". I want to use the forms as a layer of validating the data.

I now, that i can pass instance of CustomUser in my form, but i can`t do it. Need other solution.

@require_http_methods(["POST"])
@not_logged_in_user_only()
def auth(request: WSGIRequest):
    form = UserAARForm(data=request.POST)

    if not form.is_valid():
        return JsonResponse({'status': 'error', 'message': f'{form.errors.as_json()}'})

    else:
        service = AuthenticateAndAuthOrRegistrUser()
        service.execute(req=request, data=form.clean())

        if service.errors:
            return HttpResponseServerError()
        
        return redirect("profile_page")

class SoundHomeUsers(models.Model):
    email = models.EmailField(
        max_length=254, 
        unique=True, 
        validators=[UserEmailValidator().is_valid])
    password = models.CharField(
        max_length=254,
        validators=[UserPasswordValidator().is_valid])

class UserAARForm(ModelForm):
    class Meta:
        model = SoundHomeUsers
        fields = ['email', 'password']


Solution

  • I solve the problem, by extending ModelView and overriding method validate_unique. This allow me to use default ModelView validation queue, as just fields validation.

    class BaseLayerValidationForm(ModelForm):
        def validate_unique(self):
            pass
    
    class UserAARForm(BaseLayerValidationForm):
        class Meta:
            model = SoundHomeUsers
            fields = ['email', 'password']