如何通过命令在Django中更新用户资料属性?
在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等等,但都失败了,我快没有主意了。有没有更好的方法?理想情况下,我希望能够直接输入一个字典来更新用户资料,但现在我连更新一个参数都不知道怎么做。而且,即使我能创建一个只带一个参数(年龄,必填)的用户,我也无法后续更新其他参数。我不能删除旧的用户资料再新建一个,因为有外键关系。
有什么想法吗?谢谢!!!!
1 个回答
3
user.profile
是用来获取用户资料的,但你并没有尝试去 保存 这个资料。你需要把获取到的资料放到一个变量里,修改它,然后再保存。
profile = user.profile
profile.age = 34
profile.save()