gpt4 book ai didi

django - 类型错误 : __init__() got an unexpected keyword argument 'widget'

转载 作者:行者123 更新时间:2023-12-02 09:24:27 27 4
gpt4 key购买 nike

我在运行命令python manage.py runserver时遇到运行时服务器错误。终端显示错误:第 35 行,在 CustomertaskForm,startdate=forms.DateInput(widget=forms.DateField()) TypeError: init() 获得意外的关键字参数 'widget'

表单.py

class CustomertaskForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
super(CustomertaskForm, self).__init__(*args, **kwargs)

title=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'required': 'required'}))
discription=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'required': 'required'}))
startdate=forms.DateInput(widget=forms.DateField())
enddate=forms.DateInput(widget=forms.DateField())

class Meta:
model=Customertask
fields=['title','discription','startdate','enddate']

模型.py

class Customertask(models.Model):
title=models.CharField(max_length=200)
discription=models.CharField(max_length=500)
startdate=models.DateTimeField()
enddate=models.DateTimeField()

查看.py

def createtasks(request):
if request.method == 'POST':
form=CustomertaskForm(request.POST)
if form.is_valid():
tasksave=Customertask.objects.create(
customer=models.ForeignKey(Customer)
title=form.cleaned_data['title'],
discription = form.cleaned_data['discription'],
startdate=form.cleaned_data['startdate'],
enddate=form.cleaned_data['enddate']
)
tasksave.save()
return HttpResponseRedirect('/customer/tasktable')
else:
form=CustomertaskForm()
return render(request, 'customer/createtasks.html', {'form': form})

迁移是否重要,每次 models.py 或 forms.py 发生变化时......请对迁移给出明确的评论。

最佳答案

您的小部件和字段的方式是错误的 - DateField 是一个字段,DateInput 是一个小部件。因此,您的表单使用 forms.DateField(widget=forms.DateInput())。但是,由于 DateField 默认情况下使用 DateInput,因此您可以完全删除小部件参数:

class CustomertaskForm(forms.ModelForm):
...
startdate=forms.DateField()
enddate=forms.DateField()

顺便说一句,您可以通过保存模型表单来创建任务。您不需要手动调用 Customertask.objects.create():

if form.is_valid():
tasksave=form.save()
return HttpResponseRedirect('/customer/tasktable')

关于django - 类型错误 : __init__() got an unexpected keyword argument 'widget' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39998689/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com