我试过这个:
class MyClass(LoginRequiredMixin, UpdateView, ListView):
model = models.my_model
fields = ['first_model_field', 'second_model_field']
template_name = 'app/template_name.html'
extra_context = {'second_model': models.second_model.objects.get(pk=self.kwargs['pk']),#didn't work
'third_model':models.third_model.objects.get(pk='pk'),#didn't work
'fourth_model':models.fourth_model.objects.get(foreign_key_id = 'unique_kwarg')}#didn't work.
我也有包含/<int:pk>/
kwarg 和/<int:unique_kwarg>/
kwarg 的网址。
我在弄清楚如何引用网址 **kwarg 对象时遇到了麻烦。
def form_valid(self, form):
form_template_id = self.kwargs.get(self.pk_url_kwarg)
form.instance.model_id = model.objects.get(pk=form_template_id)
return super().form_valid(form)
和
def get_context_data(self, **kwargs):
"""Insert the form into the context dict."""
if 'unique_kwarg' not in kwargs:
kwargs['unique_kwarg'] = (self.kwargs.get(self.unique_kwarg))
kwargs['model_id'] = (model.objects.get(id=self.kwargs.get(self.unique_kwarg)))
return super().get_context_data(**kwargs)