Add users within application and save who added them in extended model?

I have extended user model to include table profile which has admin_id field. I would like this field populated with the user’s id if they register for the app or by the user id of the user that added them within the app.

I have created the signals to create the record in Profile.

What I want to do:

  1. A user registers and becomes a user in the app. We will call them User1 with id=1. (I want admin_id in Profile to be set to 1.)
  2. User1 logs into application and adds User2. User2 has id=2 (I want admin_id in Profile to be set to 1 since User1 added them.)

Is this possible? I have added ability to add users within the application, but I do not how to set the value of admin_id within the signals or elsewhere. Thank you.

Hi @CDogs1964, It´s not possible to get request user (current user) on signals. If you use your logic on view, for example it will be possible. You can create user and update/set admin_id using request.user.

Example:

class AddNewUser(View):
     def post(self, request, *args, **kwargs):
          form = Form(request.POST)
          if form.is_valid():
              obj = form.save()
              ...
              obj.profile.admin_id = request.user.id

Thanks @lucheol

I made the change and my view is as shown. The code runs and the user gets added along with the profile record, but admin_id is still showing as 0. Any thoughts?

@login_required
def register_admin(request):
html = ‘recruiter/register_admin.html’
if request.method == ‘POST’:
form = UserRegisterForm(request.POST)
if form.is_valid():
obj = form.save()
obj.profile.admin_id = request.user.id
return redirect(‘dashboard’)
else:
form = UserRegisterForm()
return render(request, ‘recruiter/register_admin.html’, {‘form’: form})

image

@CDogs1964, just save your object again.

if form.is_valid():
obj = form.save()
obj.profile.admin_id = request.user.id
obj.save() <--------------SAVE OBJECT AGAIN
return redirect(‘dashboard’)

Or better, obj.profile.save()

Finally got back around to this. Thank you so much…it worked!