orange freeze
orange freeze

Reputation: 11

Django rest framework create password for custom user model

Actually I'm creating an employee management system project using django rest api. Now i have created my own custom models like shown below, i want to create the register employee with the below models. But how can i set the password field for login, since I haven't included in my fields. I've attached my models and serializer. Please do help for me. I'm beginner

Class Employee (models.Model):

    name = models.CharField(max_length=50, unique=True, verbose_name='None')
   email = models.EmailField(verbose_name='Email')
department = models.CharField(max_length=30, unique=False, verbose_name='Departamento')

(And many more details like personal email,contact, and many)

# Function used to display the employee's name in the admin page
def __str__(self):
    return self.name

My serializer class is

class Employee DetailsSerializer(serializers.ModelSerializer): class Meta:

    model = Employee
    Fields = [__all__]

My views be like, i want to create register view, since i dont have password in my model, how to create password field to my above shown register field, Whatever maybe my register field should contain all those above details. I'm scratching my head here.please someone help

Upvotes: 1

Views: 379

Answers (1)

Imam Hossain Roni
Imam Hossain Roni

Reputation: 1056

Yes, you can add a password field in your Employee model but you are requested not to do it because Django already provided this type of facility. Just you have to know How to use it. Try to extend the existing User model from django.contrib.auth.models.User.Let's organize your Employee model.

from django.contrib.auth.models import User

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    #name = models.CharField(max_length=50, unique=True, 
           verbose_name='None')
    #email = models.EmailField(verbose_name='Email')
    department = models.CharField(max_length=30, unique=False, 
                 verbose_name='Departamento')
    @property
    def name(self):
        return "{0} {1}".format(self.user.first_name, 
        self.user.last_name)

No need to add an email field because this field already exists in the User model and the name field can be a property that retrieves data from the user model and the rest of the code will be unchanged. So you are concerned about the password field and it also exists in the User model.

Please check out this repo and it might help you.

Upvotes: 1

Related Questions