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

Django简易反馈表单报错:__init__()需1个参数却传入2个

解决Django类视图的TypeError: init() takes 1 positional argument but 2 were given

你的错误主要来自两个关键问题:类视图误用了函数式登录装饰器,以及URL配置未正确转换类视图为可调用函数。下面一步步帮你修复:

1. 替换@login_required为类视图专用的登录验证方式

@login_required是为函数视图设计的装饰器,直接套在类视图上会导致参数传递逻辑混乱。你需要改用Django官方推荐的LoginRequiredMixin,这是类视图的标准登录验证方案:

修改views.py:

from django.contrib.auth.mixins import LoginRequiredMixin  # 导入Mixin

class Feedback_Create(LoginRequiredMixin, BSModalCreateView):  # 把Mixin放在继承列表最前面
    template_name = 'classroom/teachers/feedback.html'
    form_class = Feedback_form
    success_message = 'Success: Feedback submitted successfully.'
    success_url = reverse_lazy('classroom:feedback_form')

如果偏爱用装饰器写法,也可以用method_decorator专门装饰类的dispatch方法:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

@method_decorator(login_required, name='dispatch')
class Feedback_Create(BSModalCreateView):
    # 其他代码保持不变

2. 修复URL配置中的类视图调用

Django的类视图不能直接在URL中引用,必须通过.as_view()方法转换为可调用的视图函数,否则无法正确实例化类:

修改urls.py:

path('feedback/', teachers.Feedback_Create.as_view(), name='feedback'),  # 添加.as_view()

额外优化点

你的feedback.html中提交按钮的类型是button,无法触发表单提交逻辑,建议改成submit:

<button type="submit" class="submit-btn btn btn-primary">Create</button>

完成以上修改后,重启Django服务器,访问页面应该就能正常加载弹窗反馈表单了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:24:18