1

RELATED: get user profile in django

The above shows how to get user profile but i read that the accepted answer method is deprecated.

How would I create/get/use user profile in django 1.9?

Community
  • 1
  • 1
ealeon
  • 12,074
  • 24
  • 92
  • 173
  • Possible duplicate of [Django get\_profile() method not working on extended User model](http://stackoverflow.com/questions/13183264/django-get-profile-method-not-working-on-extended-user-model) – Sayse Jan 27 '16 at 07:55
  • Scroll down to the second answer on duplicate... (disclaimer: its mine) – Sayse Jan 27 '16 at 07:55
  • 1
    @Sayse the .userprofile works. thanks – ealeon Jan 27 '16 at 12:41

2 Answers2

8

models.py

from django.contrib.auth.models import User
from django.db.models.signals import post_save

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    address = models.TextField()
    ......


def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

The above code will create a UserProfile record whenever a new user is created on User table. Then you can access the profile details like,

address = request.user.profile.address
Anoop
  • 2,748
  • 4
  • 18
  • 27
  • it seems to be working with address = request.user.userprofile.address instead. So when User object is being created, how do you initialize/set the address value? – ealeon Jan 27 '16 at 12:29
  • ah i just initialized it in the if created block and it works – ealeon Jan 27 '16 at 12:41
1

get_profile() method returned additional informations about User. Currently, these informations can be stored in Custom User Model or in a seperate model which is related to User Model. You can do that by simply adding one2one relation with User model to your custom User model, or by subclassing the AbstructUserBase model.

Subclassing User Model example:

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    ...

One2One Relation with User model example:

from django.contrib.auth.models import User

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    department = models.CharField(max_length=100)
ruddra
  • 50,746
  • 7
  • 78
  • 101