我有以下 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 的 ListView
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 )
显然这只会呈现上下文数据,而不是我想要使用的表单。你知道如何解决这个问题。