0

我正在尝试遵循文档并在我的模型中设置 UserProfile 表,将其与管理区域中的 User 表相关联,然后在我的用户注册时将有关我的用户的其他信息存储在此 UserProfile 表中。

views.py我有以下内容:

from django.contrib.auth import authenticate, login, logout


def register(request):
    if request.method == 'POST':
        query_dict = request.POST
        username = query_dict.__getitem__("username")
        email = query_dict.__getitem__("user_email")
        password = query_dict.__getitem__("password")
        repeat_password = query_dict.__getitem__("repeat_password")
        role = query_dict.__getitem__("role")
        user = User.objects.create_user(username, email, password)
        # django.db.models.signals.post_save gets called here and creates the UserProfile
        # I can write something like user_profile = user.get_profile() but I don't
        # know how to save information to the profile.
        user = authenticate(username=username, password=password)

        if user is not None and user.is_active:
            login(request, user)
            return HttpResponseRedirect("/")

正如您在上面代码中的注释中看到的那样,我可以检索关联的 UserProfile 对象,但我不知道从那里去哪里将附加数据(角色)存储在 UserProfile 表中。所有文档告诉我的是:

get_profile() 返回此用户的站点特定配置文件。如果当前站点不允许配置文件,则引发 django.contrib.auth.models.SiteProfileNotAvailable,如果用户没有配置文件,则引发 django.core.exceptions.ObjectDoesNotExist。

你可以在这里查看:https ://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.get_profile

但是文档没有告诉我get_profile()返回什么样的对象,或者我如何使用它在 UserProfile 表中存储信息。

4

2 回答 2

4

注意:这个答案已经过时了,Django 不再支持 AUTH_PROFILE_MODULE。请参阅此问题以获取仍然适用于最近 Django 版本的答案。

User.get_profile()AUTH_PROFILE_MODULE返回您设置的任何实例。您应该将其设置为"yourapp.UserProfile"(针对您的应用进行调整)。然后你应该能够做这样的事情:

from yourapp.models import UserProfile
profile = user.get_profile()
assert isinstance(profile, UserProfile)
profile.role = role
profile.save() # saves to DB

您实际上并不需要 import 或 assert 行 - 这只是为了让您进行健全性检查,这UserProfile就是您所期望的。

于 2012-01-17T21:29:40.833 回答
1

从您链接到的页面:

“请参阅下面有关存储其他用户信息的部分。”,指的是https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

该部分告诉您有一个设置“AUTH_PROFILE_MODULE”,它声明了 User.get_profile 将返回的模型。

您还需要遵循在 User 模型上设置 post_save 信号处理程序的说明,以便在每次创建 User 对象时自动创建配置文件模型的实例。如果你不这样做,那么 User.get_profile() 可以并且将会抛出异常。

于 2012-01-17T21:29:51.317 回答