Django - trying to access User model column field from a view

279 views
Skip to first unread message

Henry Versemann

unread,
Jan 6, 2015, 12:47:37 PM1/6/15
to django...@googlegroups.com
I currently using Python 2.7.7 and Django 1.7 as I build a new application.
I need to retrieve an entire User object from the authentication User Model, but when I do the following:

userobj = User.objects.get(username=myuser)

all I'm getting returned is just the same username value (contained in myuser) that I'm trying to use, to get the complete associated User object.
So my question is what am I doing wrong?
Can't I use a regular query on the User model (that I get from this import: "from django.contrib.auth.models import User" ) the same way that I would be able to use on one of my application's models?
This is very frustrating and while I'm comfortable with using Django apparently I still have a lot to learn about it.
Thanks for the help.

Babatunde Akinyanmi

unread,
Jan 6, 2015, 2:18:57 PM1/6/15
to Django users

userobj = User.objects.get(username=myuser)

Will get you a User object or throw an error if it can't find anything. The string representation of the User object is the string contained its username field.

Try this to confirm:
type(userobj)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b9f1b941-d01b-402a-94e9-33b2dbd13dbe%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Henry Versemann

unread,
Jan 6, 2015, 3:09:55 PM1/6/15
to django...@googlegroups.com
I tried what you suggested and printed from the view what the type command returned and it looks like this:

type(userobj)=(<class 'django.contrib.auth.models.User'>)

so that part of it does seem to be working. So why can't I see the other values within the object then displayed in normal object notation instead of just seeing this:

userobj=(hvadmin)

when I print out a string representation of the User object? I had expected to see a lot of different fields like "id", "username",  "first_name", "last_name", "email", "password", "groups",  "user_permissions", "is_staff", "is_active", "is_superuser", "last_login", and "date_joined"

which are just about all of the columns defined for the User model according to the documentation. 
So how do I get to that data then if I can't see it this way?
Thanks for the help.

James Schneider

unread,
Jan 6, 2015, 3:54:42 PM1/6/15
to django...@googlegroups.com
Not sure what you mean. The User model will act just like any other model.

$ python manage.py shell
>>> from django.contrib.auth.models import User
>>> 
>>> userobj = User.objects.get(username='jrschneider')
>>> 
>>> userobj
<User: jrschneider>
>>> 
>>> type(userobj)
<class 'django.contrib.auth.models.User'>
>>> 
>>> userobj.username
u'jrschneider'
>>> 
>>> userobj.is_staff
True
>>> 
>>> userobj.is_superuser
True
>>> 
>>> dir(userobj)
['DoesNotExist', 'Meta', 'MultipleObjectsReturned', 'REQUIRED_FIELDS', 'USERNAME_FIELD', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', u'__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', '_base_manager', '_default_manager', '_deferred', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', '_state', 'check_password', 'clean', 'clean_fields', 'date_error_message', 'date_joined', 'delete', 'email', 'email_user', 'first_name', 'full_clean', 'get_absolute_url', 'get_all_permissions', 'get_full_name', 'get_group_permissions', 'get_next_by_date_joined', 'get_next_by_last_login', 'get_previous_by_date_joined', 'get_previous_by_last_login', 'get_profile', 'get_short_name', 'get_username', 'groups', 'has_module_perms', 'has_perm', 'has_perms', 'has_usable_password', 'id', 'is_active', 'is_anonymous', 'is_authenticated', 'is_staff', 'is_superuser', 'last_login', 'last_name', 'natural_key', 'objects', 'password', 'pk', 'prepare_database_save', 'save', 'save_base', 'serializable_value', 'set_password', 'set_unusable_password', 'unique_error_message', 'user_permissions', 'username', 'validate_unique']
>>> 
>>> repr(userobj)
'<User: jrschneider>'
>>> print userobj
jrschneider
>>> 
>>> for i in dir(userobj):
...     if not i.startswith('_'):
...         print i
... 
DoesNotExist
Meta
MultipleObjectsReturned
REQUIRED_FIELDS
USERNAME_FIELD
check_password
clean
clean_fields
date_error_message
date_joined
delete
email
email_user
first_name
full_clean
get_absolute_url
get_all_permissions
get_full_name
get_group_permissions
get_next_by_date_joined
get_next_by_last_login
get_previous_by_date_joined
get_previous_by_last_login
get_profile
get_short_name
get_username
groups
has_module_perms
has_perm
has_perms
has_usable_password
id
is_active
is_anonymous
is_authenticated
is_staff
is_superuser
last_login
last_name
natural_key
objects
password
pk
prepare_database_save
save
save_base
serializable_value
set_password
set_unusable_password
unique_error_message
user_permissions
username
validate_unique
>>> 
>>> vars(userobj)
{'username': u'jrschneider', 'first_name': u'', 'last_name': u'', 'is_active': True, '_state': <django.db.models.base.ModelState object at 0x3b6c410>, 'email': u'', 'is_superuser': True, 'is_staff': True, 'last_login': datetime.datetime(2014, 11, 14, 15, 57, 27, 58040, tzinfo=<UTC>), 'password': u'pbkdf2_sha256$12000$5zwVBOTE9oft$C25SqN0TztFt6qbonqS0NVNu1WIsVUi+yuNxywMbTZA=', 'id': 1, 'date_joined': datetime.datetime(2014, 8, 8, 0, 18, 58, 7156, tzinfo=<UTC>)}
>>> 
>>> import pprint
>>> pprint.pprint(vars(userobj))
{'_state': <django.db.models.base.ModelState object at 0x3b6c410>,
 'date_joined': datetime.datetime(2014, 8, 8, 0, 18, 58, 7156, tzinfo=<UTC>),
 'email': u'',
 'first_name': u'',
 'id': 1,
 'is_active': True,
 'is_staff': True,
 'is_superuser': True,
 'last_login': datetime.datetime(2014, 11, 14, 15, 57, 27, 58040, tzinfo=<UTC>),
 'last_name': u'',
 'password': u'pbkdf2_sha256$12000$5zwVBOTE9oft$C25SqN0TztFt6qbonqS0NVNu1WIsVUi+yuNxywMbTZA=',
 'username': u'jrschneider'}
>>> 



The output of 'print userobj' is controlled by the __str__() method of the User model (inherited from AbstractBaseUser), and only returns the username. I showed a couple of different ways to enumerate the attributes and methods available on a User object via a for loop using the dir() function, and the vars() function, the latter of which is likely what you want, and will produce a consistent output rather than relying on repr() or print() (assuming the magic enumeration methods are available, which should be true for all Django models). 

For those concerned, the password field is a hash of a throwaway password on a non-Internet available development system.

HTH,

-James


Babatunde Akinyanmi

unread,
Jan 6, 2015, 4:04:06 PM1/6/15
to Django users

James said it all.
I'll just add that you really need to brush up on your python. Django is pure python. I've all been there before.

Henry Versemann

unread,
Jan 6, 2015, 4:06:42 PM1/6/15
to django...@googlegroups.com
Thanks James. You were right and its all there.
Thanks again.

Henry
Reply all
Reply to author
Forward
0 new messages