Search code examples
pythondjangodjango-modelsdjango-viewsdjango-allauth

How to create a new model object when a user signs up using django all-auth?


When a user registers, I want to create a profile object like this: profile = Profile.objects.create(username=username, points=0, age=0). Django all-auth's register view looks like this:

class SignupView(RedirectAuthenticatedUserMixin, CloseableSignupMixin,
                 AjaxCapableProcessFormViewMixin, FormView):
    template_name = "account/signup." + app_settings.TEMPLATE_EXTENSION
    form_class = SignupForm
    redirect_field_name = "next"
    success_url = '/'

    @sensitive_post_parameters_m
    def dispatch(self, request, *args, **kwargs):
        return super(SignupView, self).dispatch(request, *args, **kwargs)

    def get_form_class(self):
        return get_form_class(app_settings.FORMS, 'signup', self.form_class)

    def get_success_url(self):
        # Explicitly passed ?next= URL takes precedence
        ret = (
            get_next_redirect_url(
                self.request,
                self.redirect_field_name) or self.success_url)
        return ret

    def form_valid(self, form):
        # By assigning the User to a property on the view, we allow subclasses
        # of SignupView to access the newly created User instance
        self.user = form.save(self.request)
        try:
            return complete_signup(
                self.request, self.user,
                app_settings.EMAIL_VERIFICATION,
                self.get_success_url())
        except ImmediateHttpResponse as e:
            return e.response

    def get_context_data(self, **kwargs):
        ret = super(SignupView, self).get_context_data(**kwargs)
        form = ret['form']
        email = self.request.session.get('account_verified_email')
        email_keys = ['email']
        if app_settings.SIGNUP_EMAIL_ENTER_TWICE:
            email_keys.append('email2')
        for email_key in email_keys:
            form.fields[email_key].initial = email
        login_url = passthrough_next_redirect_url(self.request,
                                                  reverse("account_login"),
                                                  self.redirect_field_name)
        redirect_field_name = self.redirect_field_name
        redirect_field_value = get_request_param(self.request,
                                                 redirect_field_name)
        ret.update({"login_url": login_url,
                    "redirect_field_name": redirect_field_name,
                    "redirect_field_value": redirect_field_value})
        return ret

Where in this view would I write my object.create code? I find it abit hard to follow how all-auth's code is working hence why i'm asking. Here is my model if you're wondering:

class Profile(models.Model):
    username = models.CharField(max_length=32, default='AnonymousUser')
    age = models.IntegerField(default=0)
    points = models.IntegerField(default=0)

    def __str__(self):
        return self.username

Solution

  • You need to listen for the user_signed_up signal

    from allauth.account.signals import user_signed_up
    from django.dispatch import receiver
    
    @receiver(user_signed_up)
    def after_user_signed_up(request, user):
    
        profile = Profile.objects.create(username=user.username, points=0, age=0)   
    

    And your model is wrong. You should not be saving the username as a char field in your profile

    class Profile(models.Model):
        user = models.ForeignKey(User,null=True,blank=True)
        age = models.IntegerField(default=0)
        points = models.IntegerField(default=0)