0

I have a model named Customers. I want the admin to be able to add the details of each customer through admin panel. The details include username, password, company, email, etc. For password, I want to generate an auto randomly generated password field(not to be typed in admin forms), which can't be seen by admin and will be sent to the customer. I am new to Django and I can't figure out a way to do that.

EDIT

Here is the code I wrote in models.py.

class Customer(AbstractBaseUser):    
    
    def generate_password():
        #code to generate password
        return password

    customer_name = models.CharField(max_length=50)
    password = generate_password()

But I am getting same password for every customer.

Manu Vats
  • 137
  • 1
  • 8
  • This question should point you in the right direction: https://stackoverflow.com/questions/39565358/how-to-create-a-password-field-for-a-user-model-in-django?rq=1 – webtweakers May 31 '22 at 13:37
  • It doesn't help me create an auto generated password. – Manu Vats May 31 '22 at 14:04

1 Answers1

0

You can create an autogenerated password using the Django built in function make_random_password.

Its usage is also described in this post.

This function should be used outside of the class, on object creation. If you try generating the password in class, each object will have the same password from it, as it's specified inside the class.

Teo
  • 49
  • 5
  • How can I specify this in models.py because I have used this and it is creating same password for every customer. – Manu Vats May 31 '22 at 14:18
  • Having password inside your Customer model and autogenerating the password on Customer Object creation should be independent things. When the object is created (on the sign up view I guess), you should call this function to generate the password and create the Customer object with the random password before saving it. Another approach would be to use Signals, especially [pre_save method](https://docs.djangoproject.com/en/4.0/ref/signals/#django.db.models.signals.pre_save) . – Teo May 31 '22 at 14:35
  • I have update the question with the code I wrote. I hope I have explained the problem. Kindly help. – Manu Vats Jun 01 '22 at 11:27
  • You get the same password because you use the autogenerated password inside The class. That means that each object from the same class will have the same password. You need to generate the password outside the class, on object creation. – Teo Jun 01 '22 at 18:33