Files
asset-management/assetapp/forms.py
cnbugs 96023431fc feat: 新增超级管理员重置用户密码功能
- 用户列表页 /users/:支持按用户名/姓名/邮箱搜索、按状态筛选、分页
- 重置密码页 /users/<id>/password/:仅超级管理员可访问
- 复用 Django 密码校验器(一致性、长度、相似度、常见/纯数字密码)
- 管理员重置自身密码时保持登录会话不失效
- settings 补充 AUTH_PASSWORD_VALIDATORS 配置
2026-10-15 18:59:34 +08:00

73 lines
2.6 KiB
Python

from django import forms
from django.contrib.auth.password_validation import password_validators_help_text_html, validate_password
from .models import Asset, Category
class AssetForm(forms.ModelForm):
class Meta:
model = Asset
fields = [
'asset_number', 'name', 'category', 'brand', 'model', 'asset_value', 'serial_number',
'location', 'cabinet', 'cabinet_position', 'bmc_address', 'ip_address',
'has_gpu', 'gpu_type', 'gpu_count',
'purchase_date', 'warranty_expire', 'supplier',
'responsible_person', 'department', 'user', 'business_type', 'status', 'remark',
]
widgets = {
'purchase_date': forms.DateInput(attrs={'type': 'date'}),
'warranty_expire': forms.DateInput(attrs={'type': 'date'}),
'remark': forms.Textarea(attrs={'rows': 3}),
'status': forms.Select(attrs={'class': 'form-select'}),
'category': forms.Select(attrs={'class': 'form-select'}),
}
class AssetImportForm(forms.Form):
excel_file = forms.FileField(
label='Excel文件',
help_text='支持 .xlsx 格式',
widget=forms.FileInput(attrs={'accept': '.xlsx,.xls'})
)
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ['name', 'description']
class AdminPasswordResetForm(forms.Form):
"""管理员重置指定用户密码的表单"""
new_password1 = forms.CharField(
label='新密码',
widget=forms.PasswordInput(attrs={'class': 'form-control', 'autocomplete': 'new-password'}),
help_text=password_validators_help_text_html(),
)
new_password2 = forms.CharField(
label='确认新密码',
widget=forms.PasswordInput(attrs={'class': 'form-control', 'autocomplete': 'new-password'}),
)
def __init__(self, *args, target_user=None, **kwargs):
self.target_user = target_user
super().__init__(*args, **kwargs)
def clean(self):
cleaned_data = super().clean()
password1 = cleaned_data.get('new_password1')
password2 = cleaned_data.get('new_password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError('两次输入的密码不一致')
if password1 and self.target_user is not None:
validate_password(password1, self.target_user)
return cleaned_data
def save(self):
self.target_user.set_password(self.cleaned_data['new_password1'])
self.target_user.save(update_fields=['password'])
return self.target_user