I don't know what's going on here... I just want to check the value of a model field and then update it accordingly... any help or insight is appreciated!
我不知道这里发生了什么...我只是想检查模型字段的值,然后相应地更新它...任何帮助或见解表示赞赏!
model:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
beta = models.CharField(max_length=1, blank=True, null=True)
view:
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()
error:
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
2 个解决方案
#1
12
The error is "unSUBscriptable". Your user_profile object isn't a dictionary. Use user_profile.beta
, not user_profile['beta']
.
错误是“unSUBscriptable”。您的user_profile对象不是字典。使用user_profile.beta,而不是user_profile ['beta']。
#2
2
Alternatively, you can use a string with getattr:
或者,您可以使用带getattr的字符串:
getattr(user_profile, 'beta', False)
False is the default value; which, in your case would work with checking if the value is set or not. I found this very helpful, so I thought I would post this solution, even though the question was asked years ago. :)
False是默认值;在您的情况下,它将检查是否设置了值。我发现这非常有用,所以我想我会发布这个解决方案,即使这个问题是在几年前提出的。 :)
#1
12
The error is "unSUBscriptable". Your user_profile object isn't a dictionary. Use user_profile.beta
, not user_profile['beta']
.
错误是“unSUBscriptable”。您的user_profile对象不是字典。使用user_profile.beta,而不是user_profile ['beta']。
#2
2
Alternatively, you can use a string with getattr:
或者,您可以使用带getattr的字符串:
getattr(user_profile, 'beta', False)
False is the default value; which, in your case would work with checking if the value is set or not. I found this very helpful, so I thought I would post this solution, even though the question was asked years ago. :)
False是默认值;在您的情况下,它将检查是否设置了值。我发现这非常有用,所以我想我会发布这个解决方案,即使这个问题是在几年前提出的。 :)