0

I am trying to allow LDAP users to login to my Django application. Each user needs some additional attributes which I want to store in a User Profile model.

I have implemented the 'post_save' signal to create the userprofile on initial login, however, I found that with LDAP users the created flag is always False even if they have never logged in before.

The only time created = True is when I create a new superuser using manage.py

My post_save looks like this:

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    print(sender)
    print("USERPROFILE1: {0} with id {1}".format(instance, instance.pk))
    print("CREATION: {0}".format(created))
    if created:
        print("USERPROFILE3")
        UserProfile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    print("USERPROFILE2")
    instance.userprofile.save()

Upon first login, the profile is never created as 'created' is always 'False'

<class 'django.contrib.auth.models.User'>
USERPROFILE1: lbird with id 1
CREATION: False
User has no userprofile. while authenticating
[...]
django.contrib.auth.models.User.userprofile.RelatedObjectDoesNotExist: User has no userprofile.
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Well at *login* the `User` is *not* created, he is then *logged in*, so that user already exists. – Willem Van Onsem May 15 '19 at 11:47
  • But a database record is created does that not constitute 'created'? Do you have a suggestion on how I can create this profile object when an LDAP user logs in then? – Lawrence Bird May 15 '19 at 11:49
  • but it looks here that the `User` record was already created. A `User` is not created/deleted at login/logout. It looks like your LDAP system already "proactively" has constructed the users, or perhaps you do not use a database for the `User` model? – Willem Van Onsem May 15 '19 at 11:49
  • The user object did not exist before I logged in. LDAP got my user attributes and a database record was created. The user never existed in Django prior to me logging in. – Lawrence Bird May 15 '19 at 11:51

1 Answers1

0

It looks like django-auth-ldap is using its own signal to create the user and this needs a receiver function to populate the user profile model when the user first logs in.

This post has a solution which worked for me! Make sure to put the signals in their own signals.py file, configure apps.py ect, but this method has worked to create and/or populate a user profile model when a new or existing ldap user logs in.

Rod O'Connor
  • 33
  • 1
  • 8