2011-02-16 45 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

相關問題