Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django 1.3 UserProfile matching query does not exist

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

like image 371
nykon Avatar asked Mar 29 '11 19:03

nykon


2 Answers

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()
like image 147
GDorn Avatar answered Sep 30 '22 16:09

GDorn


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.

like image 33
Brian Neal Avatar answered Sep 30 '22 17:09

Brian Neal