Django:request.POST错误“ __init __()接受1个位置参数,但给出了2个”

时间:2018-07-30 06:32:54

标签: python django

我在Django项目中有一个简单的表单:

forms.py

class DamageListCriteria(forms.Form):
    fromdate = forms.CharField(widget=forms.widgets.DateTimeInput(attrs={'type': 'datetime-local'}))
    todate = forms.CharField(widget=forms.widgets.DateTimeInput(attrs={'type': 'datetime-local'}))

class Meta:
    fields = ['fromdate','todate']

views.py

class DamageListCriteria(TemplateView):
template_name = "damage/damagelist_criteria.html"

def get(self, request):
    form = DamageListCriteria()
    general = General.objects.get(pk=1)
    args = {
        'form': form,
        'general': general
    }
    return render(request, self.template_name, args)

def post(self, request):
    general = General.objects.get(pk=1)
    form = DamageListCriteria(request.POST)

    args = {
           'form': form,
           'general': general
           }
    return render(request, self.template_name, args)

urls.py

url(r'damage/list/criteria/$', views.DamageListCriteria.as_view(), name="damage-list-criteria"),

当我尝试发布时,出现此错误: '__ init __()接受1个位置参数,但给定2个位置参数'

错误出现在 form = DamageListCriteria(request.POST)代码行上。

提前感谢您的时间

2 个答案:

答案 0 :(得分:2)

这是因为您使用相同的名称定义了表单类和视图类。因此,更改视图或表单类的类名称。

或如下更改您的相应文件,

forms.py (将表单类名称更改为DamageListCriteriaForm

class DamageListCriteriaForm(forms.Form):
    fromdate = forms.CharField(widget=forms.widgets.DateTimeInput(attrs={'type': 'datetime-local'}))
    todate = forms.CharField(widget=forms.widgets.DateTimeInput(attrs={'type': 'datetime-local'}))

    class Meta:
        fields = ['fromdate', 'todate']


views.py (更改了表单类的引用)

class DamageListCriteria(TemplateView):
    template_name = "damage/damagelist_criteria.html"

    def get(self, request):
        form = DamageListCriteriaForm()
        general = General.objects.get(pk=1)
        args = {
            'form': form,
            'general': general
        }
        return render(request, self.template_name, args)

    def post(self, request):
        general = General.objects.get(pk=1)
        form = DamageListCriteriaForm(request.POST)

        args = {
            'form': form,
            'general': general
        }
        return render(request, self.template_name, args)

答案 1 :(得分:0)

您在DamageListCriteria中重新定义了views.py类。因此,您正在尝试实例化视图类,而不是实例化表单。

尝试将视图名称更改为DamageListCriteriaView,或/和将表单名称更改为DamageListCriteriaForm