您能看一下我的代码并告诉我我的错误在哪里吗?
我有一个表单类AddEditTaskForm,它具有多个字段,并且正在获取task_list以获取task.list id。
forms.py
class AddEditTaskForm(ModelForm): def __init__(self,user,*args,**kwargs): super().__init__(*args,**kwargs) task_list=kwargs.get('initial').get('task_list') self.fields['task_list'].value=kwargs['initial']['task_list'].id due_date=forms.DateField(widget=forms.DateInput(attrs={'type':'date'}),required=False) title=forms.CharField(widget=forms.widgets.TextInput()) description=forms.CharField(widget=forms.Textarea(), required=False) completed=forms.BooleanField(required=False) def clean_created_by(self): return self.instance.created_by class Meta: model = Task exclude = []
呈现表单后。我收到表格无效错误。
views.py
@login_required def list_detail(request,list_id=None,list_slug=None,view_completed=False): task_list=get_object_or_404(TaskList,id=list_id) tasks=Task.objects.filter(task_list=task_list.id) form=None if view_completed: tasks=task.filter(completed=True) else: tasks=tasks.filter(completed=False) if request.POST.getlist("add_edit_task"): form = AddEditTaskForm(request.user,request.POST,initial={'task_list':task_list}) if form.is_valid(): new_task = form.save(commit=False) new_task.created_by = request.user new_task.description = bleach.clean(form.cleaned_data["description"], strip=True) form.save() messages.success(request, 'New task "{t}" has been added.'.format(t=new_task.title)) return redirect(request.path) else: messages.success(request,'form is not valid') context={ 'list_id': list_id, 'list_slug': list_slug, 'task_list': task_list, 'tasks':tasks, 'form':form, 'view_completed':view_completed, } return render(request,'todo/list_detail.html',context)