我正在尝试构建一个基于默认Django用户构建的用户配置文件。我尝试使用以下额外字段扩展默认用户:
class MyMember(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL) #not sure about this
birthday = models.DateField()
USERNAME_FIELD = 'user' #how to use username field from default user?
REQUIRED_FIELDS = ['birthday',]
def __unicode__(self):
return self.username
但是我收到了这个错误:'经理'对象没有属性' get_by_natural_key'?为什么? 我还希望USERNAME_FIELD是默认用户的用户名。怎么样?
答案 0 :(得分:1)
这是扩展default Django User
模型的方法。您可能希望使用ForeignKey
,然后可以使用点表示法来访问User
模型的字段。
下面:
from django.contrib.auth.models import User
class MyMember(models.Model):
user = models.ForeignKey(User)
birthday = models.DateField()
def __unicode__(self):
# the default "username" field in the django user model
return self.user.username
答案 1 :(得分:1)
以下是我用于在我的演示网站中扩展UserProfile
模型的User
模型类:
#Private function required by image field.
def _get_upload_file_name_w_sub_dir(instance, filename):
return "uploaded_files/{0}{1}_{2}".format("profile_pic/", (str(time()).replace(".", "_"), filename))
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
# related_name is so you can reference *this* model as "user.profile"
# instead of "user.userprofile"
user = models.OneToOneField(User, related_name="profile")
# The additional attributes we wish to include.
year_discovered = models.IntegerField(blank=True,
verbose_name="Year you discovered Billy Joel's music/became a fan")
profile_picture = models.ImageField(upload_to=get_upload_profile_pic_file_name,
blank=True, null=True)
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user.username
以下是扩展用户模型的official documentation。