0

How to get current user's properties into dict format like given below... I tried request.user.__dict__ and request.user.__class__.__dict__ but not giving that data

{
    '_state': < django.db.models.base.ModelState object at 0x7fa2c8a14da0 > ,
    'id': 1,
    'password': 'gVFDqqWHxJhnrkyYANJb',
    'last_login': None,
    'is_superuser': False,
    'username': 'ualexander',
    'first_name': 'Valerie',
    'last_name': 'Jones',
    'email': 'gonen@yahoo.com',
    'is_staff': False,
    'is_active': True,
    'date_joined': datetime.datetime(2019, 4, 6, 10, 52, 24, 142211, tzinfo = < UTC > )
}

views.py

  def dashboard_view(request):
    print(request.user.__dict__)

my output

{'_setupfunc': <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x7fe71c6bfea0>, '_wrapped': <User: nitin>}
Nikhil Bhardwaj
  • 562
  • 10
  • 18

1 Answers1

-2

You can do this.

request.user.__class__.objects.filter(pk=request.user.id).values().first()

It will return sample output like this

{'id': 1, 'last_login': datetime.datetime(2019, 4, 5, 10, 44, 19, 110212, tzinfo=<UTC>), 'is_superuser': True, 'username': 'example', 'first_name': 'first', 'last_name': 'last', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2019, 4, 5, 9, 31, 16, 736841, tzinfo=<UTC>), 'created_at': datetime.datetime(2019, 4, 5, 9, 31, 16, 962971, tzinfo=<UTC>), 'modified_at': datetime.datetime(2019, 4, 5, 9, 31, 16, 962992, tzinfo=<UTC>), 'deleted_at': None, 'is_deleted': False, 'user_id': 1, 'password': 'pbkdf2_sha256$150000$JDcvyHbn1aFI$8gzgVZP/+bvZVQ/OISSF/+BJcJuAJE7zGU4rpBVpA8M=', 'email': 'examle@gmail.com', 'member_from': datetime.date(2019, 1, 1), 'phone_number': '011111111'}

Update: You want to get objects as dictionary for request user. In django request.user not give you data as dict format To get your desired result, You need to do some tricky task.

request.user.__class__.objects.filter(pk=request.user.id).values().first()

here request.user.__class__ is result the model name, then filter this with current user.

shafik
  • 6,098
  • 5
  • 32
  • 50
  • I don't use Django but something looks very cumbersome with `.__class__.objects.values()`. Is this actually the correct approach here? – roganjosh Apr 06 '19 at 11:35
  • I update my answer with some explanation @ Nikhil and @roganjosh – shafik Apr 06 '19 at 11:43