Search code examples
djangodjango-modelsdjango-formsdjango-admindjango-registration

Create additional model on activation django-registration


I have been struggling with implementing different answers to handle (e.g. Django-Registration & Django-Profile, using your own custom form) but have not managed to get this to work in my project because it seems too out of date.

Essentially I have installed Django-Registration in my project and can have the User authenticated and created via this.

However, I have extended the User with the following UserProfile model:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    account_type = models.IntegerField(null = True, default= 1)
    daily_message = models.BooleanField(default = True)
    tel_number = models.CharField(max_length=20, null = True)

    def __str__(self):
        return str(self.user)

And I would like that either:

  1. UserProfile with default/null values is created for each user (user can update this later)
  2. User is able to enter a telephone number with other details on registration.

The following is hooked up in my URLs.py:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('registration.backends.hmac.urls')),
    url(r'^', include('app.urls'))
]

As I have no visibility over any of the Django-registration forms and a lot of the documentation describes a custom user model (which I do not have), any ideas how I could do one of the above?


Solution

  • There are lot's of different ways in which this task can be achieved the most django like method would be to rely on a signal. More specifically the user_registered signal.

    registration.signals.user_registered Sent when a new user account is registered. Provides the following arguments:

    sender The RegistrationView subclass used to register the account.
    user A user-model instance representing the new account.
    request The HttpRequest in which the new account was registered.

    def create_user_profile(sender, user, requet):
        '''
        Creates a profile object for registered users via the
        user_registered signal
        '''
    
        obj = UserProfile.objects.get_or_create(user=user)
    

    An alternative is to subclass the RegistrationView. A second alternative is to catch the post_save signal on User.