简体   繁体   中英

Django AbstractUser password is not hashing

I've used as a model AbstractUser extended by custom fields, created form automatically by ModelForm . The problem is that, users except superuser cannot log in to system. I think it's reason, their passwords are not hashing. Where should I make it? Here are my codes.

forms.py :

class CustomUserSignUpForm(ModelForm):
    class Meta:
        model = CustomUser
        fields = ['username', 'password', 'user_image', 'role', 'branch', 'license_number', 'fin_number', 'first_name', 'last_name', 'patronymic', 'phone_number', 'email', 'voen_number', 'is_active']

views.py :

def sign_up(request):
    if request.method == 'POST':
        form = CustomUserSignUpForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = CustomUserSignUpForm()

    context = {
        'form': form,
    }

    return render(request, 'sign_up.html', context)

models.py :

class CustomUser(AbstractUser):
    patronymic = models.CharField(_('Ata adı'), max_length=150, blank=True)
    role = models.ForeignKey(Role, on_delete=models.CASCADE, blank=True, null=True)
    user_image = models.FileField(_('Profil şəkli'), upload_to='static/assets/images/user-images', blank=True)
    branch = models.ForeignKey(Branch, on_delete=models.CASCADE, blank=True, null=True)
    phone_number = models.CharField(_('Telefon'), max_length=20, blank=True)
    voen_number = models.CharField(_('VÖEN'), max_length=30, blank=True)
    fin_number = models.CharField(_('FİN'), max_length=20, blank=True)
    license_number = models.CharField(_('Lisenziya'), max_length=40, blank=True)

    def __str__(self):
        return self.username

To define a function to hash that password, you must inherited save method for you user form

    class CustomUserSignUpForm(forms.ModelForm):
    ............
    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(CustomUserSignUpForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user

This override of ModelForm is better off, because:
I check if the user exists.
I Hash de password if the password is not encoded.

class UsuarioAdmin(admin.ModelAdmin):
...

def save_model(self, request, obj, form, change):
    try:
        user_database = USUARIO.objects.get(pk=obj.pk)
    except Exception:
        user_database = None
    if user_database is None \
            or not (check_password(form.data['password'], user_database.password)
                    or user_database.password == form.data['password']):
        obj.password = make_password(obj.password)
    else:
        obj.password = user_database.password
    super().save_model(request, obj, form, change)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM