Django 用户个人资料

发布于 2024-11-08 13:40:48 字数 193 浏览 0 评论 0原文

当向用户配置文件添加其他字段(例如位置、性别、雇主等)时,我是否应该向 django.contrib.auth.models.User 添加其他列并将其保存在那里?或者我应该创建一个新表来保存用户配置文件信息?

另外,当用户上传个人资料图片时,我应该将其保存在同一个表中吗? (请注意,这不是生产服务器,我只是在本地运行服务器上执行此操作以解决问题)。谢谢

When adding additional fields to a user profile, such as location, gender, employer, etc., should I be adding additional columns to django.contrib.auth.models.User and saving it there? Or should I be creating a new table to save user profile information?

Also, when a user uploads a profile picture, should I be saving this in the same table? (Note this is not a production server, I'm just doing this on my local runserver to figure things out). Thank you

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

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

发布评论

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

评论(9

毁虫ゝ 2024-11-15 13:40:48

你必须为用户配置文件建立一个模型:

class UserProfile(models.Model):  
    user = models.ForeignKey(User, unique=True)
    location = models.CharField(max_length=140)  
    gender = models.CharField(max_length=140)  
    employer = models.ForeignKey(Employer)
    profile_picture = models.ImageField(upload_to='thumbpath', blank=True)

    def __unicode__(self):
        return u'Profile of user: %s' % self.user.username

然后在settings.py中配置:

AUTH_PROFILE_MODULE = 'accounts.UserProfile'

You have to make a model for the user profile:

class UserProfile(models.Model):  
    user = models.ForeignKey(User, unique=True)
    location = models.CharField(max_length=140)  
    gender = models.CharField(max_length=140)  
    employer = models.ForeignKey(Employer)
    profile_picture = models.ImageField(upload_to='thumbpath', blank=True)

    def __unicode__(self):
        return u'Profile of user: %s' % self.user.username

Then configure in settings.py:

AUTH_PROFILE_MODULE = 'accounts.UserProfile'
倾城月光淡如水﹏ 2024-11-15 13:40:48

从概念上讲,OneToOneField 类似于具有 unique=True 的外键,但关系的“反向”端将直接返回单个对象。这是扩展 User 类的推荐方法。

class UserProfile(models.Model):  
    user = models.OneToOneField(User)
    ...

Conceptually, OneToOneField is similar to a ForeignKey with unique=True, but the “reverse” side of the relation will directly return a single object. This is the recommended way of extending User class.

class UserProfile(models.Model):  
    user = models.OneToOneField(User)
    ...
征﹌骨岁月お 2024-11-15 13:40:48

当前 Django 是 1.9,这里是对过时的接受答案的一些更新

  1. use models.OneToOneField(User)
  2. add lated_name='profile'
  3. use .__str__()< Python 3 的 /code> 和 .format()

如下所示

class UserProfile(models.Model):  
    user = models.OneToOneField(User, related_name='profile')
    location = models.CharField(max_length=140)  
    gender = models.CharField(max_length=140)  
    ...

    def __str__(self):
        return 'Profile of user: {}'.format(self.user.username)

使用 lated_name 您可以轻松访问用户的个人资料,例如 request.user

request.user.profile.location
request.user.profile.gender

不需要额外的查找。

Current Django is 1.9 and here are some updates to the outdated accepted answer

  1. use models.OneToOneField(User)
  2. add related_name='profile'
  3. use .__str__() and .format() for Python 3

like so

class UserProfile(models.Model):  
    user = models.OneToOneField(User, related_name='profile')
    location = models.CharField(max_length=140)  
    gender = models.CharField(max_length=140)  
    ...

    def __str__(self):
        return 'Profile of user: {}'.format(self.user.username)

Using related_name you can access a user's profile easily, for example for request.user

request.user.profile.location
request.user.profile.gender

No need for additional lookups.

柒七 2024-11-15 13:40:48

Django 提供了一种将有关用户的附加信息存储在单独的文件中的方法表(称为用户配置文件)。

Django provides a way of storing additional information about users in a separate table (called user profile).

dawn曙光 2024-11-15 13:40:48

从 Django 1.5 开始,您可以使用简单的设置条目将默认 User 替换为自定义用户对象:

AUTH_USER_MODEL = 'myapp.MyUser'

有关更多详细信息,请检查此 Django 文档条目

Starting with Django 1.5 you can replace the default User with your custom user object using a simple settings entry:

AUTH_USER_MODEL = 'myapp.MyUser'

For slightly more details, check this Django documentation entry.

夏日落 2024-11-15 13:40:48

我在此处找到了一个解决方案。基本上,您只需扩展默认表单 UserCreationForm 但保持相同的名称。它与 Django 文档告诉您执行 UserProfiles 的方式无缝配合。

There's a solution I found here. Basically you just extend the default form UserCreationForm but keeping the same name. It works seamlessly with the way Django's docs tell you to do UserProfiles.

不念旧人 2024-11-15 13:40:48

可以更新答案以添加信号接收器,如果配置文件不存在,则该接收器将创建配置文件;如果配置文件已存在,则更新配置文件。

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

这个 https:// /simpleisbetterthancomplex.com/tutorial/2016/11/23/how-to-add-user-profile-to-django-admin.html 帖子还包括如何编辑、在管理面板中列出自定义配置文件。

Answer can be updated to add signal receiver which will create the profile if it does not exist and update if it is already there.

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

This https://simpleisbetterthancomplex.com/tutorial/2016/11/23/how-to-add-user-profile-to-django-admin.html post also includes how to edit, list the custom profile in admin panel.

全部不再 2024-11-15 13:40:48

当前 2 个热门答案已过时

如果您直接引用 User(例如,通过在外键中引用它),您的代码将无法在 AUTH_USER_MODEL 设置已更改的项目中运行到不同的用户模型。 [..] 当您定义外键或多对多关系到用户模型时,您应该使用 AUTH_USER_MODEL 设置指定自定义模型,而不是直接引用User

from django.conf import settings
from django.db import models

class UserProfile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="userprofile",
    )

https://docs.djangoproject.com /en/3.2/topics/auth/customizing/#referencing-the-user-model

The current 2 top answers are outdated

If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model. [..] Instead of referring to User directly [..] when you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting.

from django.conf import settings
from django.db import models

class UserProfile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="userprofile",
    )

https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#referencing-the-user-model

笑饮青盏花 2024-11-15 13:40:48

如果您想从用户对象中获取用户配置文件数据。

from django.contrib.auth.models import User
request.user.profile

If you want to get user profile data from user objects.

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