我有一个基于类的视图,该视图根据所选项目呈现一个表单集。每个项目都有一个唯一的project_id。如果不对project_id(即“ 4”)进行硬编码以替换“ None”,则会在views.py中收到由第14行(下)引起的404错误。此外,如果我不加载表单集,在第4行的form.py下对project_id进行硬编码。由于project_id需要自动传递,我如何更新它并将其传递到表单集中?谢谢。
我尝试过:
views.py
class ReqView(CreateView):
template_name = "req_view.html"
model = ProjectBudgetReq
form_class = ReqForm
def get_form_kwargs(self,*args, **kwargs):
form_kwargs = super(ReqView, self).get_form_kwargs(*args, **kwargs)
form_kwargs['project_id'] = self.kwargs.get('project_id')
print("get_form_kwargs:",form_kwargs)
return form_kwargs
def get_context_data(self,**kwargs):
project_id = kwargs.pop('project_id',None)#Line 14 404 Error
project = get_object_or_404(ProjectDetails,id=project_id)
formset = ReqFormSet(instance=project)
context = super(ReqView, self).get_context_data(**kwargs)
context['project'] = project
context['formset'] = formset
return context
def get_context_kwargs(self,**kwargs):
context_kwargs = super(ReqView,self).get_context_kwargs(*args,**kwargs)
context_kwargs['project_id'] = self.kwargs.get('project_id')
return context_kwargs
forms.py
class CreateReqForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
project_id = kwargs.pop('project_id',None) #Line 4 Formset not rendered
super(CreateReqForm,self).__init__(*args,**kwargs)
self.fields['proj_name'].queryset = ProjDesc.objects.filter(id=project_id)
self.fields['budget_desc'].queryset = ProjBudget.objects.filter(proj_name_id=project_id)
class Meta:
model = ProjBudgetReq
fields = '__all__'
BudgetReqFormSet = inlineformset_factory(ProjDesc, ProjBudgetReq, form=CreateReqForm, fields='__all__',extra=2)
问题:
views.py
#Line 14: 404 Error since it returns 'None'
forms.py
#Line 4: Formset does not render, since it's 'None'