class AdminModelForm(forms.ModelForm):
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput(render_value=True))

    class Meta:
        model = models.Admin
        fields = ['username', 'password']
        widgets = {
            'password': forms.PasswordInput(render_value=True, attrs={'class': 'form-control'}),
            'username': forms.TextInput(attrs={'class': 'form-control'}),
        }

    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if confirm_password != password:
            raise forms.ValidationError('密码不一致,请重新输入')
        return confirm_password


def admin_change(request, nid=None):
    '''添加/编辑管理员'''
    # 对象/None
    row_object = models.Admin.objects.filter(id=nid).first()

    if request.method == 'GET':
        form = AdminModelForm(instance=row_object)
        title = '编辑管理员' if row_object else '新建管理员'
        return render(request, 'change.html', {'form': form, 'title': title})

    form = AdminModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('admin_list')
    else:
        title = '编辑管理员' if row_object else '新建管理员'
        errors = form.errors.as_data()
        return render(request, 'change.html', {'title': title, 'form': form, 'errors': errors})

代码说明

  • AdminModelForm: 使用forms.ModelForm创建管理员添加/编辑表单

    • confirm_password: 添加确认密码字段
    • Meta: 设置表单模型、字段和样式
    • clean_confirm_password: 自定义验证函数,确保两次输入密码一致
  • admin_change: 处理管理员添加/编辑请求

    • row_object: 获取要编辑的管理员对象
    • request.method == 'GET': 显示表单
    • request.method == 'POST': 处理表单提交
      • form.is_valid(): 验证表单数据
      • form.save(): 保存数据

SEO优化

  • 添加了titledescription用于搜索引擎识别页面内容
  • 使用更具描述性的keywords,例如Django, forms, ModelForm, 管理员添加, 管理员编辑, 密码确认, SEO优化
  • 优化了代码中的注释,使其更易读

使用方法

  1. 将代码复制到你的Django项目中
  2. models.Admin替换为你的管理员模型
  3. 创建模板change.html用于显示表单
  4. admin_change视图链接到你的URL路由

通过以上步骤,你可以轻松创建功能完善的管理员添加/编辑页面,并优化页面内容以提升搜索引擎排名。

Django管理员添加/编辑页面-AdminModelForm

原文地址: https://www.cveoy.top/t/topic/ocb0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录