Django FormMixin 不渲染 Form

Django FormMixin does not render Form

我有以下 FormView,它适用于我当时想做的事情:

class LearningObjectiveView( LoginRequiredMixin, FormView ):
  form_class = LearningObjectiveForm
  template_name = 'learningobjective'
  success_url = reverse_lazy( 'learning_objective' )

  def get_context_data( self, **kwargs ):
    trainee = Trainee.objects.get( user = self.request.user )
    context = super( LearningObjectiveView, self ).get_context_data( **kwargs )
    context['learningobjective'] = LearningObjective.objects.filter( trainee = trainee.id )
    context['topic'] = Topic.objects.filter( trainee = trainee.id )
    return context

  def get_form_kwargs( self ):
    kwargs = super( LearningObjectiveView , self ).get_form_kwargs()
    kwargs['user'] = self.request.user
    return kwargs 

  def form_valid( self, form ):
    self.object = form.save( commit = False )
    if self.request.user.is_authenticated():
      self.object.trainee = Trainee.objects.get( user = self.request.user )
    self.object.save()
    form.save_m2m()
    return super( LearningObjectiveView, self ).form_valid( form )

因为我现在想包括分页,而且我刚刚在除 FormView 之外的每个 CBV 上看到示例,所以我想将 ListView 与 FormMixin 一起使用。

带 FormMixin 的列表视图

class LearningObjectiveView( LoginRequiredMixin, FormMixin, ListView ):
  form_class = LearningObjectiveForm
  template_name = 'learningobjective'
  model = LearningObjective
  success_url = reverse_lazy( 'learning_objective' )

  def get_context_data( self, **kwargs ):
    trainee = Trainee.objects.get( user = self.request.user )
    context = super( LearningObjectiveView, self ).get_context_data( **kwargs )
    context['learningobjective'] = LearningObjective.objects.filter( trainee = trainee.id )
    context['topic'] = Topic.objects.filter( trainee = trainee.id )
    return context

  def get_form_kwargs( self ):
    kwargs = super( LearningObjectiveView , self ).get_form_kwargs()
    kwargs['user'] = self.request.user
    return kwargs 

  def form_valid( self, form ):
    self.object = form.save( commit = False )
    if self.request.user.is_authenticated():
      self.object.trainee = Trainee.objects.get( user = self.request.user )
    self.object.save()
    form.save_m2m()
    return super( LearningObjectiveView, self ).form_valid( form )

显然这只会呈现上下文数据,而不是我想要使用的表单。你知道怎么解决这个问题吗

FormMixin 并不像您想象的那样。它所做的只是提供获取和实例化表单的方法;它不会将其添加到上下文中,也不会在提交时处理验证和保存。

您可能想要使用 ProcessFormView instead - as the docs state, despite the name this is really a mixin. However you should also bear in mind the warning on the mixins documentation 来防止尝试将来自不同通用组的 mixin 或视图混合在一起。