如何使用Djang为两种不同类型的用户创建两种不同的注册表

2024-04-19 13:13:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个项目,允许企业根据他们的位置添加本地商店。有一个登记表,为企业已经建立了扩展用户模型,并使用电子邮件帐户验证。到目前为止,这个功能运行得非常好。你知道吗

这是我的型号.py

class Profile(models.Model):
user = models.OneToOneField(User)
activated_key = models.CharField(max_length=120, null=True)
activated = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

def send_activation_email(self):
    if not self.activated:
        self.activated_key = code_generator()
        self.save()
        path_ = reverse('activate', kwargs={'code': self.activated_key})
        subject = 'Activa tu cuenta :)'
        from_email = settings.DEFAULT_FROM_EMAIL
        message = 'Activa tu cuenta haciendo click aquí' + path_
        recipient_list = [self.user.email]
        html_message = '<h1>Activa tu cuenta haciendo click <a href="{path_}"aquí</a>.</h1>'.format(path_=path_)
        print(html_message)

        sent_mail = False
        return sent_mail

def post_save_user_receiver(sender, instance, created, *args, **kwargs):
if created:
    profile, is_created = Profile.objects.get_or_create(user=instance)

post_save.connect(post_save_user_receiver, sender=User)

我的商业模式是:

class Business(models.Model):
owner = models.OneToOneField(User, null=False)
name = models.CharField(max_length=75)
logo = models.ImageField(null=True, blank=False, upload_to=upload_location)

这是我在表格.py

class RegisterForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

class Meta:
    model = User
    fields = ('username', 'email',)

def clean_email(self):
    email = self.cleaned_data.get('email')
    qs = User.objects.filter(email__iexact=email)
    if qs.exists():
        raise forms.ValidationError('Este email ya se está usando por otro usuario. Prueba con otro.')
    return email

def clean_password2(self):
    # Check that the two password entries match
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError("Passwords don't match")
    return password2

def save(self, commit=True):
    # Save the provided password in hashed format
    user = super(RegisterForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    user.is_active = False
    # create a new user hash for activating email.

    if commit:
        user.save()
        print(user.profile)
        user.profile.send_activation_email()

    return user

接下来我要完成的是为用户(不是企业)创建另一个注册表单,这些用户只能在businessdetailview上发表评论。理想情况下,这些用户可以注册社交帐户和电子邮件,但这些用户应该在另一个SQL表中,并且与企业没有关系。你知道吗

我读过很多关于在django中有多个用户的文章,这似乎是一个困难的任务。我可以采用不同的方法:

  • 在我的房间里有另一个模型型号.py但我认为这会给我的商业模式带来问题
  • 为用户和其他企业创建另一个应用程序,但我以前从未这样做过
  • 使用AbstractUser,但这涉及到共享主注册表窗体,我希望为每种类型的用户提供不同的窗体。你知道吗

我怎么能做到?你知道吗

提前谢谢!你知道吗


Tags: 用户selffalsetruemodelsemailsavedef