Y
Y
Yakov Feldman2018-11-01 22:24:11
Django
Yakov Feldman, 2018-11-01 22:24:11

How to customize user creation in Django?

Django has standard user creation tools, I used
this trick before

class SignUp(generic.CreateView):
    form_class = UserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

But in the current project, it is not the user himself who creates a login-password for himself, but a "senior in rank",
for example, a director creates a login for a teacher and a tutor, and a tutor for a parent and a student.
The user type is stored in Profile
When creating a login, an additional choice appears, it depends on who creates, for example, a tutor can choose between a parent and a student when creating.
I tried to extend the form and implement an extra field like this
class SignUpFormTut(UserCreationForm):
    role = forms.ChoiceField(
        choices = (
            ('P','Родитель'),
            ('S','Ученик'),
        )
    )

class SignUpTut(generic.CreateView):
    form_class = SignUpFormTut
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

the field appears in the form but how to use the value?
There was an idea to insert the code into the signal function, this one,
but it does not work yet
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yura Khlyan, 2018-11-07
@jfeldman

You can add logic to the method form_validto create a profile. Look in the docks what this method does (it only creates a User + returns a response)
You can also send a signal to the user's save post. But signals are harder to test and debug. It can be something like this:

def create_profile(sender, instance, created, **kwargs):
    """ Creates profile for user """
    CustomerProfile.objects.get_or_create(user=instance)


post_save.connect(create_profile, sender=USER_MODEL)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question