当我尝试将数据保存到UserProfile中的字段时,Django引发了一个类型错误。
我认为我正确扩展了UserProfile。
我的userProfile模型:
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True, related_name='profile')
....
initials = models.CharField(max_length=5)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
在我的设置中,我添加了:
AUTH_PROFILE_MODULE = 'timepiece.UserProfile'
当我运行一个应该将值插入User的继承字段的测试时,我得到一个TypeError:
(erp)BAir:website jorrit$ ./manage.py test timepiece.PivotalTest.test_update_users
Creating test database for alias 'default'...
E
======================================================================
ERROR: test_update_users (timepiece.tests.pivotal.PivotalTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/jorrit/virtualenvs/erp/erp/apps/timepiece/tests/pivotal.py", line 73, in test_update_users
UserProfile.sync_pivotal_users(self.tracker, 450001)
File "/Users/jorrit/virtualenvs/erp/erp/apps/timepiece/models.py", line 44, in sync_pivotal_users
initials = m.initials,)
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 365, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0])
TypeError: 'username' is an invalid keyword argument for this function
----------------------------------------------------------------------
Ran 1 test in 1.857s
经过测试的功能:
def sync_pivotal_users(tracker, project_id):
members = tracker.get_memberships_project(project_id)
for m in members:
#check if member exist in db
try:
#to know if m.id exists in current db
UserProfile.objects.get(pivotal_member_id=m.id)
#if not then create a new user
except UserProfile.DoesNotExist:
u = UserProfile(pivotal_member_id = m.id,
username = m.name, #code breaks here
email = m.email, # and here
initials = m.initials,)
u.save()
答案 0 :(得分:0)
the approach outlined in the documentation背后的想法是,当创建新的User
对象时,您附加一个处理程序,该处理程序又创建一个UserProfile
对象:
方法get_profile()如果不存在,则不会创建配置文件。您需要为User模型的django.db.models.signals.post_save信号注册一个处理程序,并且在处理程序中,如果创建为True,则创建关联的用户配置文件
所以在你的循环成员中,你应该创建User
个对象,而不是UserProfile
个对象,因为它们将通过信号自动创建。
您是如何获取密码(注册过程)并不是很清楚,但是一旦获得密码,您就可以使用
更新该用户的配置文件profile = current_user_obj.get_profile()
profile.initial = "some value"
profile.save()