Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

python - Random password generation when admin creates employees in admin site

I have inherited three users from the User model, namely the Admin, Employee, and Relative.

models.py

config = RawConfigParser()
config.read('config.cfg')

class UserManager( BaseUserManager):
    
    def _create_user(self, PAN_ID, password=None, **extra_fields):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not PAN_ID:
            raise ValueError('Users must have a PAN_ID')
        extra_fields['email'] = self.normalize_email(extra_fields["email"])
        user = self.model(PAN_ID=PAN_ID, **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_user(self, PAN_ID, password=None, **extra_fields):

        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(PAN_ID, password, **extra_fields)
    
    def create_superuser(self, PAN_ID, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(PAN_ID, password, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
        
    PAN_ID = models.CharField(max_length=100, unique=True)
    password = models.CharField(_('password'), max_length=128, null=False, blank=True)
    email = models.EmailField(max_length=100, unique=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    name = models.CharField( max_length=60, blank=True)
    address = models.CharField(max_length=70, null=True, blank=True)
    holding = models.CharField(max_length=100, null=True, blank=True)
    
    is_staff = models.BooleanField(
        _('staff status'),
        default=True,
        help_text=_(
            'Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    
    objects = UserManager()

    USERNAME_FIELD = "PAN_ID"
    EMAIL_FIELD = "email"
    REQUIRED_FIELDS = ['email', 'name', 'holding']
    

    
class Admin(User):
    pass    
    
    
class Employee(User):
    designation = models.CharField(max_length=89, null=True)
    
    
class Relative(User):
    reference = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name="creator")

admin.py

from django.contrib import admin
from base.models import Admin, Employee, Relative, User
from django import forms
from django.contrib.auth.models import Group
from mass import settings
from django.core.mail import send_mail
from abc import ABC
from django.utils import timezone
from django.dispatch.dispatcher import receiver
from  django.db.models.signals import post_save

@receiver(post_save, sender=Employee)
@receiver(post_save, sender=Relative)
def mail(sender,instance, *args, **kwargs ):
   subject = "Hi"
   message  = f"Your password is {instance.password} " 
   from_email = None
   recipient_list = [instance.email]
   send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None) 

class RandomPasswordAndEmailMixin:
    def save(self, commit=True):
        if not self.instance.pk:
            instance = super().save(commit=False)
            instance.set_password(User.objects.make_random_password())
            return instance.save()
        else:
            self.cleaned_data.pop("password")
            return super.save(commit)
                
class UserModelForm(forms.ModelForm):
    

    class Meta:
        exclude = ('is_staff', 'is_active', 'password')
        
        
class EmployeeModelForm(RandomPasswordAndEmailMixin, UserModelForm):
    class Meta(UserModelForm.Meta):
        model = Employee
          
@admin.register(Employee)        
class EmployeeModelAdmin(admin.ModelAdmin, RandomPasswordAndEmailMixin):
    form = EmployeeModelForm
    

The Admin will be the superuser. The Admin will go to the admin site and perform CRUD on Employees and Relatives. In the form, there I just want the Admin to enter an Employee/Relative's username(PAN_ID), password, and email. On clicking 'Save', the corresponding signal for the mail should be sent and email would be sent so the password should be accessible in the mail function. The password should be generated automatically by make_password. I 'm getting the following error.

Internal Server Error: /admin/base/employee/add/ Traceback (most recent call last): File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangocorehandlersexception.py", line 47, in inner response = get_response(request) File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangocorehandlersase.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangocontribadminoptions.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangoutilsdecorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangoviewsdecoratorscache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangocontribadminsites.py", line 233, in inner return view(request, *args, **kwargs) File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangocontribadminoptions.py", line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangoutilsdecorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangoutilsdecorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangocontribadminoptions.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangocontribadminoptions.py", line 1580, in _changeform_view self.save_model(request, new_object, form, not add) File "C:UsersDellOneDriveDesktopdjangodevvenvlibsite-packagesdjangocontribadminoptions.py", line 1093, in save_model obj.save() AttributeError: 'NoneType' object has no attribute 'save' [22/Jan/2021 15:13:17] "POST /admin/base/employee/add/ HTTP/1.1" 500 112227

question from:https://stackoverflow.com/questions/65842901/random-password-generation-when-admin-creates-employees-in-admin-site

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try to fix the else clause to super().save(commit).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...