Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

accounts.admin中管理员创建普通博客账号时重构的save方法中user.source = 'adminsite'不生效 #733

Open
4 of 6 tasks
JOYCAT-Q opened this issue Jul 16, 2024 · 0 comments

Comments

@JOYCAT-Q
Copy link

JOYCAT-Q commented Jul 16, 2024

我确定我已经查看了 (标注[ ][x])


我要申请 (标注[ ][x])

  • BUG 反馈
  • 添加新的特性或者功能
  • 请求技术支持

accounts.admin中的class BlogUserCreationForm(forms.ModelForm)

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        print("commit: ", commit)
        if commit:
            user.source = 'adminsite'
            user.save()
        return user

输出结果为 "commit: ", False
使得if判断后的语句无法正常执行,具体表现为用户的source设置失效

commit 参数为 False 的原因:
Django 管理员中,添加一个新用户时,ModelAdmin 会调用表单的 save_model() 方法来保存模型实例。这个方法通常不会直接调用表单的save()方法,而是接收一个已经保存(但可能未提交到数据库)的模型实例作为参数。

解决方法:在class BlogUserAdmin(UserAdmin)中重构方法

class BlogUserAdmin(UserAdmin):
    form = BlogUserChangeForm
    add_form = BlogUserCreationForm
    # 重构父类方法
    def save_model(self, request, obj, form, change):
        # 如果不是变更操作(即添加新对象)
        if not change:
            # 可以在这里设置额外的字段值
            obj.source = 'adminsite'
            # 调用父类的 save_model 方法来保存对象
        super().save_model(request, obj, form, change)
# 其他不变

同时将之前判断注释掉:

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        # if commit:
        #     user.source = 'adminsite'
        #     user.save()
        return user

修改前后对比:
屏幕截图 2024-07-16 144119

当前大体环境配置:
Django==4.2.14
Windows10
MySQL==8.0

@JOYCAT-Q JOYCAT-Q changed the title 管理员创建普通博客账号时重构的save方法中user.source = 'adminsite'不生效 accounts.admin中管理员创建普通博客账号时重构的save方法中user.source = 'adminsite'不生效 Jul 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant