本文介绍了django 1.3 UserProfile匹配查询不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我的用户模型有一个小问题,该模型如下所示:

I have a small problem with User model, the model looks like this:

#! -*- 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)

当我打开django-shell并首先导入用户时:

When I open a django-shell and first import a user :

u = User.objects.get(id = 1)

然后:

zm = UserProfile.objects.get(user = u)

我得到一个错误:

DoesNotExist:不存在UserProfile匹配查询.

DoesNotExist: UserProfile matching query does not exist.

这个想法很简单,首先我创建了一个用户,它起作用了,然后我想向该用户添加一些信息,但它不起作用:/

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:/

推荐答案

您确定该用户的UserProfile对象存在吗?Django不会自动为您创建它.

Are you sure that UserProfile object for that user exists? Django doesn't automatically create it for you.

您可能想要的是这样:

u = User.objects.get(id=1)
zm, created = UserProfile.objects.get_or_create(user = u)

如果您确定配置文件存在(并且您已经正确设置了AUTH_PROFILE_MODULE),则用户模型已经具有帮助方法来处理此问题:

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:

u = User.objects.get(id=1)
zm = u.get_profile()

这篇关于django 1.3 UserProfile匹配查询不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 20:55