4

Problem

I'm trying to get the variable website out of a class UserProfile that is linked to MyUser via an OneToOneField.

To do so i tried in the python manage.py shell

from models import *

myuser = MyUser.objects.get(email="dummy@domain.tld")
myuser_profile = UserProfile(user=myuser)

myuser_profile.website

But this returns me u'' instead of the website address that i can see on my admin site. Is this not the correct way to access the variable or need I to look some where else for the failure?

Configuration

models.py

class MyUserManager(BaseUserManager):
    def create_user(self, email, password=None):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(email, password=password)
        user.is_admin = True
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser):
    email = models.EmailField(verbose_name='email address', max_length=255, unique=True,)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):            # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

    def __unicode__(self):
        return self.email


class UserProfile(models.Model):
    # This line is required. Links UserProfile to a User model instance.
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                related_name='MyUser'
                                )

    # The additional attributes we wish to include.
    website = models.URLField(blank=True)


    # Override the __unicode__() method to return out something meaningful!
    def __unicode__(self):
        return self.user.email

admin.py

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    max_num = 1
    can_delete = False

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Permissions', {'fields': ('is_admin',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2')
        }),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()

    inlines = [UserProfileInline]


    # Now register the new UserAdmin...
    admin.site.register(MyUser, UserAdmin)
rwx
  • 696
  • 8
  • 25

1 Answers1

6

You are creating a new instance of UserProfile instead of loading the existing one from the database.

You can access OneToOne relations using

myuser = MyUser.objects.get(email="dummy@domain.tld")
profile = myuser.userprofile   # access the onetoone relation
profile.website   

You find out more about OneToOne relations in the django docs

ilse2005
  • 11,189
  • 5
  • 51
  • 75
  • If i try to do this i get an error on step two when doing `profile = myuser.userprofile`: `AttributeError: 'MyUser' object has no attribute 'userprofile'` – rwx Feb 22 '16 at 16:46
  • 1
    hm. Try to remove the "related_name" attribute from the OneToOne field? – ilse2005 Feb 22 '16 at 16:48
  • 2
    Now it works - do you know why it works without the `related_name` attribute? I added this because of a SO answer about how to [reverse access onetoone fields](http://stackoverflow.com/questions/11088901/django-onetoone-reverse-access) – rwx Feb 22 '16 at 16:55
  • 4
    `related_name` references how you access `UserProfile` from the related object (in your case) `MyUser`. So you could access the relation with `myuser.myuser`, which doesn't make sense. You should skip `related_name` or choose a better name like `userprofile` – ilse2005 Feb 22 '16 at 16:57