django 1.3 UserProfile matching query does not exist

怎甘沉沦 提交于 2021-02-18 07:07:23

问题


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)

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

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.

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


回答1:


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

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:

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



回答2:


As discussed in the documentation, Django does not automatically create profile objects for you. 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.



来源:https://stackoverflow.com/questions/5477925/django-1-3-userprofile-matching-query-does-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!