Search code examples
djangopython-3.xdjango-signals

Django signals for two types of users


I'm trying to build an app that will have two different user types. Currently I have one type of user called - Tenant Profiles. I'm trying to add in Landlord Profiles type also. Both profiles are derived from Django's in-built auth_users. I have taken last_name field from auth_users to True or False and I'm trying to build Landlord/Tenant profiles based on this condition. I have tried to modify the signals.py file, but have had no luck so far.

With code attached below it allows you register, but only creates account for auth_users. If I use commented code in signals.py it will create Tenant Profile.

signals.py

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Tenant_Profile, Landlord_Profile


# This function aims to create a profile everytime a user registers
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
     #if created:
         #Tenant_Profile.objects.create(tenant=instance)
     if created and User.last_name == False:
            Tenant_Profile.objects.create(tenant=instance)
     elif created and User.last_name == True:
             Landlord_Profile.objects.create(landlord=instance)



# kwargs just accepts any additional keyword arguments on the end of the function
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    #instance.tenant_profile.save()
    if User.last_name == False:
        instance.tenant_profile.save()
    elif User.last_name == True:
        instance.landlord_profile.save()

views.py

def register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            last_name = form.cleaned_data.get('last_name')
            #print(type(username))
            #print(type(last_name))
            messages.success(request, f'Your account has been created! You are now able to log in')
            return redirect('login')
    else:
        form = UserRegistrationForm()
    return render(request, 'users/register.html', {'form': form}) 

Solution

  • As Willen Van Onsem rightly said you need to follow what he is saying and just to answer your question

    You have to use instance.last_name instead.