2011-02-16 47 views
1

在Django中,添加与用户关联的附加信息的标准方式是使用用户配置文件。要做到这一点,我已经叫一个应用程序, “占”如何使用命令更新Django用户配置文件中的属性?

accounts 
    __init__.py 
    models.py 
     admin.py (we'll ignore this for now, it works fine) <br> 
     management 
      __init__.py 
      commands 
       __init__.py 
       generate_user.py 

settings.py中,我们有AUTH_PROFILE_MODULE = 'accounts.UserProfile'

在models.py我们

from django.db import models 
from django.contrib.auth.models import User 
# Create your models here.  
class UserProfile(models.Model): 
    user = models.ForeignKey(User, unique=True) 
    age=models.IntegerField() 
    extra_info=models.CharField(max_length=100,blank=True) 
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])  

最后一行使用python装饰器来获取用户配置文件对象,如果它已经存在,或者返回现有的配置文件对象。此代码取自: http://www.turnkeylinux.org/blog/django-profile#comment-7262

接下来,我们需要尝试使我们的简单命令。因此,在gen_user.py

from django.core.manaement.base import NoArgsCommand 
from django.db import models 
from django.contrib.auth.models import User 
from accounts.models import UserProfile 
import django.db.utils 


class Command(NoArgsCommand): 
help='generate test user' 
def handle_noargs(self, **options): 
    first_name='bob'; last_name='smith' 
    username='bob' ; email='[email protected]' 
    password='apple' 
    #create or find a user 
    try: 
     user=User.objects.create_user(username=username,email=email,password=password) 
    except django.db.utils.IntegrityError: 
     print 'user exists' 
     user=User.objects.get(username=username) 
    user.firstname=first_name 
    user.lastname=last_name 
    user.save() #make sure we have the user before we fiddle around with his name 
    #up to here, things work. 
    user.profile.age=34 
    user.save() 
    #test_user=User.objects.get(username=username) 
    #print 'test', test_user.profile.age 
    #test_user.profile.age=23 
    #test_user.save() 
    #test_user2=User.objects.get(username=username) 
    #print 'test2', test_user2.profile.age 

运行,从你的项目目录,键入python manage.py gen_user

的问题是,为什么不岁时更新?我怀疑这是一个例子,我抓到 一个实例,而不是真实的对象,下注 我试过从使用user.userprofile_set.create到使用setattr等尝试的所有东西都失败了, 。有更好的模式吗?理想情况下,我想只能用字典来更新用户配置文件,但现在我看不到如何更新单个参数。另外,即使我已经能够创建具有一个参数的用户(年龄,这是必需的),我也无法以后更新附加参数。由于外键关系,我无法删除或删除旧的用户配置文件,也无法删除旧的用户配置文件。

想法?谢谢!!!!

回答

3

user.profile检索配置文件,但你从来没有尝试过实际上保存它。将结果放入一个变量中,进行变异,然后保存。

profile = user.profile 
profile.age = 34 
profile.save() 
+0

很抱歉说得这么慢,但我有以下几点: user.profile.age = 34 user.save() – 2011-02-16 03:22:11

相关问题