为什么我的数据看起来像这样?我可以在 user_id 中设置值吗?如果我删除 def create_user_profile,它将创建 nama、nik、电子邮件、nomor_hp。但 user_id 为空在图片中,我在没有 def create_user_profile 的情况下创建了 id 1 和 2,而在我使用 def create_user_profile 时创建了 id 3,4,5,6这是我的模型.pyclass Profile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) nama = models.CharField(max_length=30, blank=True) nik = models.CharField(max_length=30, blank=True) email = models.EmailField(max_length=75, blank=True) nomor_hp = models.TextField(max_length=15, blank=True) def __str__(self): return self.user@receiver(post_save, sender=User)def create_user_profile(sender, instance, created, **kwargs): try: instance.profile.save() except ObjectDoesNotExist: Profile.objects.create(user=instance)这是我创建用户的views.py,我在这里犯错了吗?def signup(request): if request.method == 'POST': user_form = UserCreationForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) profile = profile_form.save(commit=False) user.is_active = False user.save() profile.save() uidb64 = urlsafe_base64_encode(force_bytes(user.pk)) domain = get_current_site(request).domain link=reverse('activate', kwargs={ 'uidb64': uidb64, 'token': token_generator.make_token(user)}) activate_url = 'http://'+domain+link email_body = 'Hallo '+user.username + 'Tolong gunakan link ini untuk verifikasi akun anda\n' +activate_url email_subject = 'Aktivasi Akun Anda' email = EmailMessage( email_subject, email_body, 'noreply@kantorkecamatanbintanutara.com', [profile.email], )
1 回答
红糖糍粑
TA贡献1815条经验 获得超6个赞
您的signup视图和信号都会成为一个Profile对象,更糟糕的是,在后者中您不会链接到用户。
我建议放弃创建Profile. 它没有多大用处。如果您稍后编辑Profile,您应该简单地保护它,此外您应该确保当您创建一个User对象时,您只是正确地链接它。例如:
def signup(request):
if request.method == 'POST':
user_form = UserCreationForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
profile_form.instance.user = user
profile = profile_form.save()
# …
# …
添加回答
举报
0/150
提交
取消