Django-allauth - Override the default login form

I use this code (in forms.py) for my custom registration form for allauth:

class RegistrationForm(UserCreationForm): birth_date = forms.DateField(widget=extras.SelectDateWidget(years=BIRTH_DATE_YEARS)) class Meta: model = get_user_model() fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name', 'gender', 'birth_date', 'city', 'country') 

Of course, I pointed out ACCOUNT_SIGNUP_FORM_CLASS in settings.py to point to this form, and it displays the fields that I put into it. However, it does not work on presentation, even if I set the signup method, it will never be called. I tried using save , but it’s the same anyway - an error occurs when one of my added fields is empty when creating a user and saving it to the database. So what is the right code for this?

+5
source share
2 answers

I did this thanks to @rakwen , who found the right solution here . I wrote my custom adapter and put it in adapters.py in my application:

 from allauth.account.adapter import DefaultAccountAdapter class AccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=False): data = form.cleaned_data user.username = data['username'] user.email = data['email'] user.first_name = data['first_name'] user.last_name = data['last_name'] user.gender = data['gender'] user.birth_date = data['birth_date'] user.city = data['city'] user.country = data['country'] if 'password1' in data: user.set_password(data['password1']) else: user.set_unusable_password() self.populate_username(request, user) if commit: user.save() return user 

Then I pointed ACCOUNT_ADAPTER in settings.py to point to this adapter, and it finally started working!

+12
source

In project.py setup try adding this line:

check if you added this:

 AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) ACCOUNT_SIGNUP_FORM_CLASS = "yourapp.forms.customSignupForm" 

In app.models

 class CustomModel(models.Model): """CustomModel docstring.""" city = forms.CharField(max_length=75) country = forms.CharField(max_length=25) other.... 

In app.forms:

 class SignForm(forms.ModelForm): """SignForm docstring.""" username = forms.CharField( max_length=30, ) first_name = forms.CharField( max_length=30, ) last_name = forms.CharField( max_length=30, ) field... def myclean(): def signup(self, request, user): """You signup function.""" # dont forget to save your model class Meta: model = mymodel.CustomModel fields = [ 'city', 'country', 'field...', ] 

Try this method!

+3
source

Source: https://habr.com/ru/post/1246659/


All Articles