Django注册和多个配置文件

Ste*_*Ste 10 django registration profiles

我在我的应用程序中使用django-registration.我想创建具有不同配置文件的不同类型的用户.例如,一个用户是教师而另一个用户是学生.

如何修改注册以设置user_type并创建正确的配置文件?

Chr*_*ris 12

答案很长:p

我发现The Missing Manual的帖子对于这类问题非常宝贵,因为它解释了django-profiles和django-registration系统的许多功能.

我建议在允许通过AUTH_PROFILE_MODULE设置的单个配置文件上使用多表继承

例如

#models.py
class Profile(models.Model):
    #add any common fields here (first_name, last_name and email come from User)

    #perhaps add is_student or is_teacher properites here
    @property
    def is_student(self):
        try:
            self.student
            return True
        except Student.DoesNotExist:
            return False

class Teacher(Profile):
    #teacher fields

class Student(Profile):
    #student fields
Run Code Online (Sandbox Code Playgroud)

django-registration使用信号通知您注册.您应该在此时创建配置文件,以便您确信对user.get_profile()的调用将始终返回配置文件.使用的信号代码是

#registration.signals.py
user_registered = Signal(providing_args=["user", "request"])
Run Code Online (Sandbox Code Playgroud)

这意味着在处理该信号时您可以访问所请求的信息.因此,当您在POST时,注册表单中包含一个字段,用于标识要创建的用户类型.

#signals.py (in your project)
user_registered.connect(create_profile)

def create_profile(sender, instance, request, **kwargs):
    from myapp.models import Profile, Teacher, Student

    try:
        user_type = request.POST['usertype'].lower()
        if user_type == "teacher": #user .lower for case insensitive comparison
            Teacher(user = instance).save()
        elif user_type == "student":
            Student(user = instance).save()
        else:
            Profile(user = instance).save() #Default create - might want to raise error instead
    except KeyError:
        Profile(user = instance).save() #Default create just a profile
Run Code Online (Sandbox Code Playgroud)

如果要向创建的模型添加任何内容(默认字段值未涵盖),则在注册时,您可以明显地从请求中提取该内容.