运行命令python manage.py runserver
时出现运行时服务器错误。终端显示错误:
第35行,在CustomertaskForm中,startdate = forms.DateInput(widget = forms.DateField())TypeError: init ()得到了一个意外的关键字参数' widget'
forms.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']
models.py
class Customertask(models.Model):
title=models.CharField(max_length=200)
discription=models.CharField(max_length=500)
startdate=models.DateTimeField()
enddate=models.DateTimeField()
view.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中进行更改时,请明确注释迁移。
答案 0 :(得分:3)
您的小部件和字段方式错误 - 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')
答案 1 :(得分:0)
在表单中尝试此操作。
Forms.py
widgets = {
'Title': forms.TextInput(attrs={'class': 'form-control','required':'required'}),
'Description': forms.TextInput(attrs={'class': 'form-control','required':'required'}),
'StartDate': forms.DateInput(attrs={'class': 'form-control', 'type': 'date','required':'required'}),
'EndDate': forms.DateInput(attrs={'class': 'form-control', 'type': 'date','required':'required'}),
}