我有一个使用基于类的视图呈现的表单集。我已经阅读了django文档,并看到了与此相关的一些答案,但我无法使其正常工作。
下面的project_id = kwargs.pop('project_id',None)
函数中的def get_context_data
出现404错误。
当下面的project_id = kwargs.pop('project_id',None)
函数中的def __init__(self,*args,**kwargs)
时,表单集完全不呈现。
project_id
是id
模型中自动生成的ProjectDetails
。
如何将project_id
传递给表单集?
models.py
class ProjectDetails(models.Model):
project_name = models.CharField(max_length = 50,blank = False)
client = models.CharField(max_length = 200,blank = False)
class ProjectFinance(models.Model):
project_name = models.ForeignKey(ProjectDetails,on_delete = models.CASCADE, null =
True,blank=False)
finance_item = models.CharField(max_length = 50,null=True,blank=False)
forms.py
class FianceForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
project_id = kwargs.pop('project_id',None)
super(FianceForm,self).__init__(*args,**kwargs)
class Meta:
model = ProjectFinance
fields = '__all__'
FinanceFormSet= inlineformset_factory(ProjectDetails, ProjectFinance, form=FianceForm, fields='__all__',extra=2)
views.py
class FinanceView(CreateView):
template_name = "project.html"
model = ProjectFinance
form_class = FianceForm
def get_form_kwargs(self,*args, **kwargs):
form_kwargs = super(FinanceView, self).get_form_kwargs(*args, **kwargs)
form_kwargs['project_id'] = self.kwargs.get('project_id')
return form_kwargs
def get_context_data(self,**kwargs):
project_id = kwargs.pop('project_id',None)
project = get_object_or_404(ProjectDetails,id=project_id)
formset = FinanceFormSet(instance=project)
context = super(FinanceView, self).get_context_data(**kwargs)
context['project'] = project
return context
谢谢。