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