我遵循了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 )
由于我现在想要包含分页,我只是在每个CBV上看到了示例,但是FormView,我想使用带有FormMixin的ListView。
使用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 )
显然,这只会呈现上下文数据,但不会呈现我想要使用的表单。你知道如何解决这个问题。
答案 0 :(得分:1)
FormMixin不会按照您的想法执行操作。它所做的就是提供获取和实例化表单的方法;它不会将其添加到上下文中,也不会在提交时验证并保存它。
您可能想要使用ProcessFormView
- 正如文档所述,尽管名称这实际上是一个混合。但是,您还应该记住mixins documentation警告不要试图混合使用不同通用组的mixins或视图。