我有两个布尔类型的用户的自定义用户模型:
class User(AbstractUser):
"""User model."""
username = None
email = models.EmailField(unique=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,12}$')
phone = models.CharField(validators=[phone_regex], max_length=17)
is_trainer = models.BooleanField(default=False)
is_client = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['phone']
objects = UserManager(
还有两个使用OneToOneField的不同模型。任何modells的字段都不相似。
培训师模型
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
...
*and more then 20 another fields*
...
客户端型号:
class Client(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='client')
....
....
我想在新用户注册时,根据他在SignUpForm中选择的哪个配置文件(培训师客户端),创建了适当的模型。 为此,我发出了信号
@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
if created:
if sender.is_trainer:
profile = Profile.objects.create(user=instance)
else:
profile = Client.objects.create(user=instance)
instance.profile.save()
但始终创建用户+培训师。我该如何修理它?
添加我的SignUpForm:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your blog account.'
message = render_to_string('reg/acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
'token':account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponseRedirect('/reg/success_signup/')
else:
form = SignUpForm()
return render(request, 'reg/signup.html', {'form': form})
答案 0 :(得分:1)
@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
"""
sender: sender model from which you'll receive signal from
instance: model instance(record) which is saved (it will be instance of sender model)
"""
if created: # used to perform action only at creation time (avoid the code to execute during any update)
if instance.is_trainer: # access the field of instance
profile = Profile.objects.create(user=instance) # you have correctly passed instance to foreign key and you just need to check condition for the same
else:
profile = Client.objects.create(user=instance)
# not necessary to call .save() here.. because when you used create method of profile or client object it is created and saved, as you haven't changed any field or value of instance you don't need to save instance