问题
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