Django 注册和多个配置文件

发布于 2024-09-07 04:49:23 字数 122 浏览 4 评论 0原文

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

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

I'm using django-registration in my application. I want to create different kinds of users with different profiles.
For example, one user is a teacher and another user is a student.

How can I modify registration to set the user_type and create the right profile?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤云独去闲 2024-09-14 04:49:23

长答案:p

我发现缺失的手册帖子对于此类问题解释了 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

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

#registration.signals.py
user_registered = Signal(providing_args=["user", "request"])

这意味着在处理该信号时您可以访问所发出的请求。因此,当您发布注册表时,请包含一个字段来标识要创建的用户类型。

#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

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

Long answer :p

I've found The Missing Manual post invaluable for this kind of problem as it explains many of features of the django-profiles and django-registration systems.

I'd suggest using multi table inheritance on the single profile you're allowed to set via the AUTH_PROFILE_MODULE

For instance

#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 uses signals to notify you of a registration. You should be creating the profile at that point so you are confident that calls to user.get_profile() will always return a profile.
The signal code used is

#registration.signals.py
user_registered = Signal(providing_args=["user", "request"])

Which means when handling that signal you have access to the request made. So when you POST the registration form include a field that identifies what type of user to create.

#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

If you want to add anything to the model that is created, that isn't covered by default field values, at registration time you can obviously pull that from the request.

守望孤独 2024-09-14 04:49:23

http://docs.djangoproject.com/en/1.2/topics/auth/ #groups

Django 组是定义您要查找的内容的好方法。
您可以拥有一个用户扩展配置文件 将包含教师和学生的所有属性。

class MasterProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    # add all the fields here

然后定义组:教师学生,并将每个 MasterProfile 与教师或学生关联。

Django 组表可以帮助您定义各种角色并将用户正确分配到组。

http://docs.djangoproject.com/en/1.2/topics/auth/#groups

Django groups are a great way to define what you are looking for.
You can have one User extended profile that will contain all attributes of teachers and students.

class MasterProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    # add all the fields here

Then define groups: teacher and student and you associate each MasterProfile to either a teacher or a student.

Django Group table can help you define your various roles and allocate users to groups correctly.

却一份温柔 2024-09-14 04:49:23

我遇到了同样的问题,我尝试了克里斯建议的答案,但它对我不起作用。

我只是 Django 的新手,但我认为处理程序 create_profile 所采用的参数应该与信号 user_registered 下的 providing_args 下的参数相匹配,并且在克里斯的回答他们不(我认为它们可能与信号 post_save 传递的信号相匹配,我在他引用的《缺失手册》中看到了该信号的使用)

我修改了他的代码以使 args 匹配:

def create_profile(sender, **kwargs):
    """When user is registered also create a matching profile."""

    request, instance = kwargs['request'], kwargs['user']

    # parse request form to see whether profile is student or teacher
    try:
        user_type = request.POST['usertype'].lower()
        print(user_type)
        if user_type == "teacher": #user .lower for case insensitive comparison
            Teacher(user = instance).save()
        elif user_type == "student":
            Student(user = instance).save()
        else:
            Userprofile(user = instance).save() #Default create - might want to raise error instead
    except KeyError:
        Userprofile(user = instance).save() #Default create just a profile

并且似乎现在正在工作

I had the same issue and I tried the answer suggested by Chris, however it didn't work for me.

I'm only a newbie in Django, but I think the args taken by handler create_profile should match those under providing_args by signal user_registered, and in Chris's answer they don't (I think they probably match those passed by signal post_save, which I've seen used in the Missing Manual that he quotes)

I modified his code to make args match:

def create_profile(sender, **kwargs):
    """When user is registered also create a matching profile."""

    request, instance = kwargs['request'], kwargs['user']

    # parse request form to see whether profile is student or teacher
    try:
        user_type = request.POST['usertype'].lower()
        print(user_type)
        if user_type == "teacher": #user .lower for case insensitive comparison
            Teacher(user = instance).save()
        elif user_type == "student":
            Student(user = instance).save()
        else:
            Userprofile(user = instance).save() #Default create - might want to raise error instead
    except KeyError:
        Userprofile(user = instance).save() #Default create just a profile

and seems to be working now

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文