You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中超级用户评论表单作者字段设置及隐藏报错求助

解决Django评论表单超级用户字段隐藏与默认值设置的错误

错误原因

  • 视图实例化表单时未传递user参数,导致kwargs.get("user")返回None,调用is_superuser触发AttributeError
  • 未将user从kwargs中移除就传给父类ModelForm,会因父类不识别该参数引发额外错误

解决方案

1. 修改表单类的__init__方法

先从kwargs中取出user(避免传递给父类),再做权限判断:

class CreateComment(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ["author", "text"]

    def __init__(self, *args, **kwargs):
        # 取出user参数,默认值为None
        user = kwargs.pop('user', None)
        super(CreateComment, self).__init__(*args, **kwargs)
        
        # 验证用户已登录且为超级用户
        if user and user.is_authenticated and user.is_superuser:
            self.fields["author"].widget = forms.HiddenInput()
            self.fields["author"].initial = "admin"

2. 更新视图中的表单实例化代码

创建表单时必须传递当前请求的user对象:

def article_view(request, article_id):
    # 其他业务逻辑...
    form = CreateComment(user=request.user)
    # 其他业务逻辑...

补充说明

  • 添加user.is_authenticated判断,避免未登录用户(AnonymousUser)触发的异常
  • 使用pop('user', None)保证即使未传user参数,表单也能正常初始化

内容的提问来源于stack exchange,提问作者Ravdar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 10:35:34