30π
It depends what you are trying to add to the model. If you want to add more information about the user, then it is generally recommended that you use the UserProfile
method: http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
However, if you just want to add custom methods or managers to the User
model, I would say that itβs more logical to use a proxy model, like so:
from django.contrib.auth.models import User
class UserMethods(User):
def custom_method(self):
pass
class Meta:
proxy=True
A proxy model will operate on the same database table as the original model, so is ideal for creating custom methods without physically extending the model. Just replace any references to User
in your views to UserMethods
. (And of course you can use this in the admin tool by unregistering the User
model and registering your proxy model in its stead.)
Any instances of the original User
model that are created will be instantly accessible via the UserMethods
model, and vice-versa. More here: http://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models
(NB. Proxy models require Django 1.1 and above)
14π
if you want to add custom methods to the User model, I would recommend monkey_patching:
create a file monkey_patching.py
in any of your apps
::
#app/monkey_patching.py
from django.contrib.auth.models import User
def get_user_name(self):
if self.first_name or self.last_name:
return self.first_name + " " + self.last_name
return self.username
User.add_to_class("get_user_name",get_user_name)
and import it in appβs __init__.py
file. ie::
#app/__init__.py
import monkey_patching
- [Django]-The right place to keep my signals.py file in a Django project
- [Django]-Django rest serializer.data is an empty OrderedDict()
- [Django]-Django error <model> object has no attribute 'update'
4π
Yes. No need to mess with the foundations when your user model has a .get_profile() function attached to it.
- [Django]-Django and postgresql schemas
- [Django]-Django β Model graphic representation (ERD)
- [Django]-Concurrency control in Django model
3π
2013 update:
in 1.5 you can sustitute a custom User model and add whatever you want https://docs.djangoproject.com/en/dev/topics/auth/customizing/#auth-custom-user
- [Django]-Django string to date format
- [Django]-Django Admin: How to access the request object in admin.py, for list_display methods?
- [Django]-Best place to clear cache when restarting django server
-1π
I prefer to use the same UserProfile across various projects I develop and extend User for any project-specific needs. So, common functionality goes to UserProfile, and project-specific functionality goes to custom User. I have not had any adverse effects of having a subclassed User model yet, I wonder if there still exist any with Django 1.0+.
- [Django]-Get rid of get_profile() in a migration to Django 1.6
- [Django]-How to 'clear' the port when restarting django runserver
- [Django]-How to debug Django commands in PyCharm