Django注册和多个配置文件

标签 django registration profiles

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

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

最佳答案

长答案:p

我发现The Missing Manual发布对于这种问题非常有值(value),因为它解释了django配置文件和django注册系统的许多功能。

我建议您在允许通过AUTH_PROFILE_MODULE设置的单个配置文件上使用multi table inheritance

例如

#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

django-registration使用信号通知您注册。您应该在那时创建配置文件,以便确信对user.get_profile()的调用将始终返回配置文件。
使用的信号代码是
#registration.signals.py
user_registered = Signal(providing_args=["user", "request"])

这意味着在处理该信号时,您可以访问所发出的请求。因此,当您发布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

如果要向创建的模型添加默认字段值未涵盖的任何内容,则在注册时显然可以将其从请求中拉出。

关于Django注册和多个配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3100521/

相关文章:

Django:仅显示用户自己的数据

php - 注册功能

Spring Batch 和 Spring3.1 配置文件

MySQL:我在网站中的哪里存储每个用户的个人资料信息?

java - 根据多个 Spring 配置文件定义 bean

django - 如何在 Django URL 模式中捕获子域?

python - 为什么这段 Python (Django) 代码会占用内存?

python - 有没有一种方法可以检查设置并仅在设置了该设置后才运行测试?

authentication - 实现网站注册登录+OpenID的多种方式

powershell - 使用 AZ Powershell 模块注册 native 应用程序