Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom fields to users in Django

Tags:

python

django

I am using the create_user() function that Django provides to create my users. I want to store additional information about the users. I tried following the instructions given at

http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

but I cannot get it to work for me. Is there a step-by-step guide that I can follow to get this to work?

Also, once I have added these custom fields, I would obviously need to add / edit / delete data from them. I cannot seem to find any instructions on how to do this.

like image 574
Gaurav Sharma Avatar asked May 22 '10 04:05

Gaurav Sharma


People also ask

Can we add fields in user model in Django?

Extending the existing User model If you wish to store information related to User , you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user.

How do I create a custom field in Django?

Look at the existing Django fields (in django/db/models/fields/__init__.py ) for inspiration. Try to find a field that's similar to what you want and extend it a little bit, instead of creating an entirely new field from scratch. Put a __str__() method on the class you're wrapping up as a field.


1 Answers

The recommended way is to create a new model and give it a OneToOneField() with the built-in User model like so:

class Student(models.Model):     user = models.OneToOneField(User)     college = models.CharField(max_length=30)     major = models.CharField(max_length=30) 

etc.

Then you can access the fields like this:

user = User.objects.get(username='jsmith') college = user.student.college 
like image 116
rigdonmr Avatar answered Sep 24 '22 08:09

rigdonmr