2011-01-06 31 views
2

我不知道這是怎麼回事這裏...我只是想檢查的模型字段的值,然後相應地更新它...任何幫助或洞察力的讚賞!對象不可識別是什麼意思?

模型:

class UserProfile(models.Model): 
    user = models.ForeignKey(User, unique=True) 
    beta = models.CharField(max_length=1, blank=True, null=True) 

視圖:

from internal.accounts.models import UserProfile 
from django.contrib.auth.models import User 
@login_required  
def beta_testers(request): 
    user = User.objects.get(username=request.user.username) 
    user_profile = user.get_profile() 

    count = UserProfile.objects.filter(beta='1').count() 

    if count < 50 and not user_profile['beta']: 
     user_profile['beta'] = '1' 
     user_profile.save() 

錯誤:

TypeError at /utilities/beta-signup/ 
'UserProfile' object is unsubscriptable 
Request Method: GET 
Request URL: http://localhost/utilities/beta-signup/?x=1&y=15 
Django Version: 1.2.1 
Exception Type: TypeError 
Exception Value:  
'UserProfile' object is unsubscriptable 
Exception Location: C:/django\internal\cms_helper\views.py in beta_testers, line 284 
+1

的可能重複[在Python,這是什麼意思,如果對象是標化的或不?(http://stackoverflow.com/questions/216972/in-python-what-does-it-mean-如果-AN-對象是,腳標有或沒有) – mipadi 2011-01-06 17:30:08

回答

7

錯誤是 「unSUBscriptable」。你的user_profile對象不是一個字典。使用user_profile.beta,而不是user_profile['beta']

+0

哦,是的,這一定是它。謝謝。 – 2011-01-06 17:32:33

0

另外,也可以使用帶有getattr的字符串:

getattr(user_profile, 'beta', False) 

假是默認值;在你的情況下,它可以檢查值是否設置。我發現這非常有幫助,所以我想我會發布這個解決方案,即使這個問題是在幾年前提出的。 :)