Hybrid
Hybrid

Reputation: 7049

How to Override .signup() on Django-Allauth Form

I am trying to override .signup() on a form that inherits from django-allauth's SignupForm, but it does not seem to be working. My main goal is to save an instance of the UserProfile model at the same time as saving the User model.

Here is the code I have so far:

class MySignupForm(SignupForm):
    """ This form only used for django-allauth package (called in Settings.py) """
    first_name = forms.CharField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'First name'}))
    last_name = forms.CharField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Last name'}))
    dob = forms.CharField(widget=forms.TextInput(attrs={'type': 'date', 'min': '1940-01-01', 'max': '2030-01-01'}))  # HTML5 Widget... works?

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        login_url = reverse_lazy('account_login')

        self.helper = FormHelper()
        self.helper.layout = Layout(
            Div('first_name', css_class='col-md-6'),
            Div('last_name', css_class='col-md-6'),
            Div('dob', css_class='col-md-12', style='clear: both'),
            Div('username', css_class='col-md-12', style='clear: both'),
            Div('email', css_class='col-md-12'),
            Div('password1', css_class='col-md-12', style='clear: both'),
            Div('password2', css_class='col-md-12'),
            HTML('<div class="col-md-12"><br></div>'),

            FormActions(
                Submit('submit', 'Register', css_class='btn btn-primary', style='display:block;clear:both;margin: 0 0 15px 15px;float:left'),
                HTML('<a href="{0}" class="btn btn-default" style="margin: 0 15px 15px 0;float:right;display:inline">Sign In</a>'.format(login_url))
            )
        )

    def signup(self, request, user):
        print(form.cleaned_data['dob'])
        return user 

As you can see, I am trying to print() the dob, but when I try signing up, nothing shows up in my terminal! Any help would be appreciated.

Upvotes: 0

Views: 726

Answers (1)

doniyor
doniyor

Reputation: 37904

you need this in your settings.py

ACCOUNT_SIGNUP_FORM_CLASS = 'yourproject.yourapp.forms.SignupForm'

EDIT:

you can just use the post_save signal to create userprofile instance

from django.db.models.signals import post_save

@receiver(post_save, sender=User, weak=False, dispatch_uid='models.create_userprofile')
def create_userprofile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

Upvotes: 2

Related Questions