两种类型用户的 Django 信号

Django signals for two types of users

我正在尝试构建一个具有两种不同用户类型的应用程序。目前我有一种类型的用户称为 - 租户配置文件。我也在尝试添加 Landlord Profiles 类型。这两个配置文件都来自 Django 的内置 auth_users。我已将 last_name 字段从 auth_users 更改为 True 或 False,我正在尝试根据此条件构建 Landlord/Tenant 配置文件。我试图修改 signals.py 文件,但到目前为止还没有成功。

下面附有代码,您可以注册,但只能为 auth_users 创建帐户。如果我在 signals.py 中使用注释代码,它将创建租户配置文件。

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}) 

正如 Willen Van Onsem 所说的那样,您需要按照他所说的来回答您的问题

您必须改用 instance.last_name