want to extend auth_user model in django by adding two fields - django

in django,i want to extend the auth_user model and adding the 2 fields.one is created_user which will display the date and time when user created something and other is modified_user which will display the date n time when modification is done..
is it possible by migration??
i ve tried dis code..
from django.contrib.auth.models import User, UserManager
class CustomUser(User):
created_user= models.DateTimeField("date and time when created")
modified_user=models.DateTimeField("date and time when modified")
objects= UserManager()

I suggest reading the documentation on creating your own custom user model.
In your particular case, the easiest thing would probably be to subclass AbstractUser and add your fields as above.
If you’re entirely happy with Django’s User model and you just want to add some additional profile information, you can simply subclass django.contrib.auth.models.AbstractUser and add your custom profile fields. This class provides the full implementation of the default User as an abstract model.

Related

django - Extending `auth.models.User` and usering login, logout

If I create a CustomUser model which inherits from django.contrib.auth.models.User, like so:
in models.py
class CustomUser(django.contrib.auth.models.User):
customfield = TextField()
...
Should I still be able to use
django.contrib.auth.{authenticate, login, logout} in the normal way? Do I have to make some additional configuration change? I know these methods only work on User objects, but technically my CustomUser is-a User.
Currently, authenticate(username=u, password=p) is always returning None, even with valid credentials.
Since Django 1.5 (officially but it doesn't worked for me) and "stable" in 1.6 there is a functionality to extend the User model in a clean way.
At first:
-> Take care that you load the User model only via:
from django.contrib.auth import get_user_model
User = get_user_model()
-> Once you have built the database theres no easy way to change the User model. The database relations will break and Django / South isn't able to fix it.
-> third party modules have to be compatible with that new layout and refer in it's models to "get_user_model()", too.
You have to add some Code for the admin to respect your new model:
See: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model
To Override the model you need to inherit from AbstractBaseUser:
from django.contrib.auth.models import AbstractBaseUser
class MyUser(AbstractBaseUser):
...
date_of_birth = models.DateField()
height = models.FloatField()
...
REQUIRED_FIELDS = ['date_of_birth', 'height']
AbstractBaseUser provides you all attributes of the default user model. So you don't have to take care of email, username, first_name, last_name, password etc.
More info about overriding the user model: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.models.CustomUser
In your settings link your new model:
AUTH_USER_MODEL = 'customauth.MyUser'
Please read the whole documentation of customizing the user model, there are some interesting hints for overriding the default manager, admin forms etc. Just remember that bigger changes in an existing project can be a big pain.
A short overview:
- Extend models.AbstractUser
- Set AUTH_USER_MODEL in settings.py
All details can be found here: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model

When to use the Custom User Model in Django 1.5

I have a question regarding the custom user model in Django 1.5
So right now the default user model looks just fine to me, I just need to add a few other variables such as gender,location and birthday so that users can fill up those variables after they have successfully registered and activated their account.
So, what is the best way to implement this scenario?
Do I have to create a new app called Profile and inherit AbstractBaseUser? and add my custom variable to models.py? Any good example for me to follow?
thank you in advance
You want to extend your user model to the AbstractUser and add your additional fields. AbstractUser inherits all of the standard user profile fields, whereas AbstractBaseUser starts you from scratch without any of those fields.
It's hard to define best practices this close to the release, but it seems that unless you need to drastically redefine the User model, then you should use AbstractUser where possible.
Here are the docs for extending the User model using AbstractUser
Your models.py would then look something like this:
class MyUser(AbstractUser):
gender = models.DateField()
location = models.CharField()
birthday = models.CharField()
MyUser will then have the standard email, password, username, etc fields that come with the User model, and your three additional fields above.
Then you need to add the AUTH_USER_MODEL to your settings.py:
AUTH_USER_MODEL = 'myapp.MyUser'

Django admin inlines on default list page?

I have a table that only has a handful of entries in it, and it'd be nice if I could use inlines for their list instead of forcing staff to click through to the edit page each time.
That is, when someone clicks on the link that ordinarily gives a list of the model objects, they should instead see the model objects displayed inline.
I tried something like this, but unsurprisingly it gives an error because there's no foreign key:
class MyModelInline(admin.StackedInline):
model = MyModel
class MyModelAdmin(admin.ModelAdmin):
inlines = [MyModelInline,]
admin.site.register(MyModel, MyModelAdmin)
For it to work as you've described you'll need an "editor" model to be a parent for the data. All the rows you want to display should have a foreign key to a single 'editor' model object. So, in models.py:
from django.db import models
class Editor(models.Model):
pass
class MyModel(models.Model):
name = models.CharField(max_length=100) # Field added for demonstration
# ... add any other fields you like ...
editor = models.ForeignKey(Editor)
And in admin.py:
from django.contrib import admin
from Test.models import Editor, MyModel
class MyModelInline(admin.StackedInline):
model = MyModel
class EditorAdmin(admin.ModelAdmin):
inlines = [MyModelInline,]
admin.site.register(Editor, EditorAdmin)
Some other things to consider:
When you make a new MyModel() object programmatically you must always set the foreign key to point to the editor. There should only be one instance of the editor for this to work as you've described. When using the admin interface, this foreign key should be set automatically by using the admin page for the editor object. I would suggest restricting creation and deletion of editor objects for everyone except yourself in production. If someone deletes the editor object then all MyModel objects disappear as well.
Alternative options:
1) If the edits the admin staff is doing are simple then I would recommend implementing "actions" instead.
2) There's also the possibility of overriding the admin template. I personally like this option less because every time Django is updated I have to check that my changes aren't interfering with new features. However, sometimes this is the only way to do some more advanced things in the admin interface. I've done this in my own project, but like to keep the changes minimal.

inheritance from the django user model results in error when changing password

I inherited form the django user model like so:
from django.db import models
from django.contrib.auth.models import User, UserManager
from django.utils.translation import ugettext_lazy as _
class NewUserModel(User):
custom_field_1 = models.CharField(_('custom field 1'), max_length=250, null=True, blank=True)
custom_field_2 = models.CharField(_('custom field 2'), max_length=250, null=True, blank=True)
objects = UserManager()
When i go to the admin and add an entry into this model, it saves fine, but below the "Password" field where it has this text "Use '[algo]$[salt]$[hexdigest]' or use the change password form.", if i click on the "change password form' link, it produces this error
Truncated incorrect DOUBLE value: '7/password'
What can i do to fix this?
The best way to extend Django's User model is to create a new Profile model and identify it through the AUTH_PROFILE_MODULE setting. See http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/, and http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
This adds a get_profile() method to User instances which retrieves your associated model for a given User.
While doable (I did it once and regret it) using inheritance to extend the User model is not the best idea. I'd suggest you take Chris' advice and extend the User model with 1-1 relationship as it is the "standard" and "supported" way of doing it, and the way reusable apps deal with user profiles. Otherwise you need to implement an authentication backend if you want to do it by inheritance. So if you MUST do it see this. But be warned, you'll stumble across other problems later.

Cannot assign - must be a "UserProfile" instance

I have a class UserProfile defined which takes the default user as a foreign key.
Now another class A has a foreign key to UserProfile.
So for saving any instance in class A, how do i give it the userprofile object.
Also, does making a class UserProfile mean that class user is still used and class UserProfile is just some other table?
I need to know this as I have to take care of the user profile creation, so I should know what gets stored where?
--
Confused
So for saving any instance in class A,
how do i give it the userprofile
object.
Create a app with a model which has a models.OneToOneField(User) or a models.ForeignKey(User, unique=True).
Make your project aware of your UserProfile by pointing to it from the settings.py file AUTH_PROFILE_MODULE = 'myapp.UserProfile'.
Read the documentation.
Also, does making a class UserProfile
mean that class user is still used and
class UserProfile is just some other
table?
Yes, your database will have both a auth_user and a user_profile table. This is due to the fact that using UserProfiles doesn't mean all user have to have profiles. Only the additional fields defined in the UserProfile model will be in the user_profile table.
I need to know this as I have to take
care of the user profile creation, so
I should know what gets stored where?
James Bennett created two nice apps which with a few hours of careful reading will be of great help especially when it comes to the user registration part. Go look at django-registration and django-profiles.
I assume your UserProfile model is intended to store additional information about your users. If so, there's documentation about the best approach to do this, which in brief is:
define a model with fields for the additional information you'd like to store, or additional methods you'd like to have available, and also add a OneToOneField from your model to the User model. This will ensure only one instance of your model can be created for each User.
Set AUTH_PROFILE_MODULE to myapp.MyModel, where myapp is the app containing the model MyModel which you want to use to store extra information about your users.