如何使用命令更新Django中用户配置文件中的属性?

时间:2011-02-16 00:17:05

标签: python django-models

在Django中,添加与用户关联的其他信息的标准方法是使用用户配置文件。为此,我有一个名为“accounts”的应用程序

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='bob@bob.com'
    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等的一切都失败了,我的想法已经用完了。有更好的模式吗?理想情况下,我希望只能输入一个dict来更新userprofile,但是现在,我看不到如何更新单个参数。此外,即使我能够使用一个参数(年龄,这是必需的)创建用户,我以后也无法更新其他参数。由于foreignkey关系,我无法删除或删除旧的userprofile和blast。

想法?感谢!!!!

1 个答案:

答案 0 :(得分:3)

user.profile检索个人资料,但您无法尝试实际保存。将结果放入变量中,将其变异,然后保存。

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