如何在创建新用户时创建用户配置文件

时间:2015-02-10 20:49:33

标签: python django django-models

我使用django 1.7.4作为我的角度应用程序的服务器。我需要为用户存储更多数据,因此我添加了UserProfile模型。

models.py

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    company_name = models.CharField(max_length=100)

我想测试一下shell的工作原理。

如何在创建用户时创建用户个人资料?

我试过了:

>>> u = User.objects.create(username="testing123", email="testing123@gmail.com")
>>> u.userprofile.create(company_name="onetwo")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/bhaarat/.virtualenvs/djangorest/lib/python2.7/site-packages/django/db/models/fields/related.py", line 428, in __get__
    self.related.get_accessor_name()
RelatedObjectDoesNotExist: User has no userprofile.

1 个答案:

答案 0 :(得分:2)

您正在尝试访问相关对象,而当您执行u.userprofile

时它不存在

尝试使用与创建User对象相同的方法:

UserProfile.objects.create(user=u, company_name="onetwo")