[英]django 1.3 UserProfile matching query does not exist
I have a small problem with User model, the model looks like this: 我对User模型有一个小问题,模型看起来像这样:
#! -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
url = models.URLField(max_length = 70, blank = True, verbose_name = 'WWW')
home_address = models.TextField(blank = True, verbose_name = 'Home Adress')
user = models.ForeignKey(User, blank = True, unique = True)
def __unicode__(self):
return '%s' %(self.user)
When I open a django-shell and first import a user : 当我打开一个django-shell并首先导入一个用户时:
u = User.objects.get(id = 1)
and then : 然后 :
zm = UserProfile.objects.get(user = u)
I get an error: 我收到一个错误:
DoesNotExist: UserProfile matching query does not exist. DoesNotExist:UserProfile匹配查询不存在。
The idea is simple, first I create a user, it works, then I want to add some informations to the user, it dosn't work:/ 这个想法很简单,首先我创建一个用户,它有效,然后我想向用户添加一些信息,它不起作用:/
Are you sure that UserProfile object for that user exists? 您确定该用户的UserProfile对象是否存在? Django doesn't automatically create it for you.
Django不会自动为您创建它。
What you probably want is this: 你可能想要的是这个:
u = User.objects.get(id=1)
zm, created = UserProfile.objects.get_or_create(user = u)
If you're sure the profile exists (and you've properly set AUTH_PROFILE_MODULE), the User model already has a helper method to handle this: 如果您确定该配置文件存在(并且您已正确设置AUTH_PROFILE_MODULE),则User模型已经有一个帮助方法来处理:
u = User.objects.get(id=1)
zm = u.get_profile()
As discussed in the documentation , Django does not automatically create profile objects for you. 正如文档中所讨论的 ,Django不会自动为您创建配置文件对象。 That is your responsibility.
这是你的责任。 A common way to do that is to attach a post-save signal handler to the User model, and then create a profile whenever a new user is created.
一种常见的方法是将保存后信号处理程序附加到用户模型,然后在创建新用户时创建配置文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.