O
O
orexov6662020-08-22 18:13:24
Django
orexov666, 2020-08-22 18:13:24

How to edit django allauth validation?

The project has a django-allauth battery, added a new phone field to the User which is unique=True
Added a field to forms.py

from allauth.account.forms import SignupForm
from allauth.account.forms import forms
from .models import CustomUser


class MyCustomSignupForm(SignupForm):
    """Форма регистрации"""
    def __init__(self, *args, **kwargs):
        super(MyCustomSignupForm, self).__init__(*args, **kwargs)
        self.fields['phone'] = forms.CharField(required=True)
        self.fields['image'] = forms.FileField(required=False)



    def save(self, request):
        user = super(MyCustomSignupForm, self).save(request)
        user.phone = self.cleaned_data['phone']
        if self.cleaned_data['image']:
            user.image = self.cleaned_data['image']
        user.save()
        return user

    def clean_phone(self):
        if CustomUser.objects.filter(phone=self.cleaned_data["phone"]).exists():
            self.add_error("phone", forms.ValidationError("ERROR"))
        return self.cleaned_data["phone"]

brought the field into the template, when registering, even if there is no such number, it gives Traceback UNIQUE constraint failed: users_customuser.phone

I want it to add an error to forms.error and display it on the page

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-09-01
@tumbler

In your custom user, you need to declare the phone field of the model as unique. A ModelForm-based form will be able to check the uniqueness of the entered value, for "manual" forms, I'm afraid this must be written manually

def validate_phone(value):
    try:
        CustomUser.objects.get(phone=value)
        raise ValidationError("занят")
    except CustomUser.DoesNotExist:
        return value

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question