我有一个基于LeagueTransferForm表单的名为LeagueTransferView的FormView。

我试图覆盖get_context_data以添加额外的播放器以在模板中呈现。

但是永远不会到达get_context_data。在其他视图(例如DetailView,ListView等)上工作正常

我想念什么吗?

在我的配置之下

视图

class LeagueTransferView(FormView):
    template_name = 'hockey/league/transfer_market.html'
    form_class = LeagueTransferForm
    success_url = ''

    def get_context_data(self, **kwargs):
        print('----NEVER REACHED----')
        context = super(LeagueTransferView, self).get_context_data(**kwargs)
        petitioner = get_object_or_404(Team, user=self.request.user.profile, league=self.kwargs['pk'])
        context['players'] = Player.objects.filter(leagues=self.kwargs['pk']).exclude(teams=petitioner)
        return context

    def get(self, request, *args, **kwargs):
        petitioner = get_object_or_404(Team, user=self.request.user.profile, league=self.kwargs['pk'])
        form = self.form_class(initial={'league': self.kwargs['pk'], 'petitioner': petitioner})
        form.fields['offered_player'].queryset = petitioner.players
        return render(request, self.template_name, {'form': form})

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            transfer = form.save(commit=False)
            team = Team.objects.filter(league=transfer.league, players__in=[transfer.requested_player])
            if not team:  # free agent
                transfer.status = 1
                messages.success(request, _('transfer succeeded'))
            else:
                print(team)
                transfer.player_owner = team[0]
                if transfer.petitioner.user is None:  # bot team
                    transfer.status = 1
                    messages.success(request, _('transfer succeeded'))
                else:
                    messages.success(request, _('transfer waiting for confirmation by player owner'))
            transfer.save()
            return HttpResponseRedirect(reverse('hockey_dashboard'))

        petitioner = get_object_or_404(Team, user=self.request.user.profile, league=self.kwargs['pk'])
        form.fields['offered_player'].queryset = petitioner.players
        return render(request, self.template_name, {'form': form})


形成

class LeagueTransferForm(forms.ModelForm):
    class Meta:
        model = Transfer
        fields = ['league', 'requested_player', 'offered_player', 'player_owner', 'petitioner']
        labels = {
            'requested_player': _('Requested player'),
            'offered_player': _('Offered player'),
        }
        widgets = {
            'requested_player': forms.HiddenInput,
            'league': forms.HiddenInput,
            'player_owner': forms.HiddenInput,
            'petitioner': forms.HiddenInput
        }

最佳答案

您的代码永远不会到达get_context_data(),因为您已经覆盖了get()方法并且没有在其中调用get_context_data()函数。在代码中将get_context_data()传递给context时,您需要手动调用render()函数。

我不建议您尝试以下方法,而不是过度使用get()并返回您的自定义响应,而只需覆盖必要的内容,让Django处理其余内容即可。

class LeagueTransferView(FormView):
    template_name = 'hockey/league/transfer_market.html'
    form_class = LeagueTransferForm
    success_url = ''

    def get_context_data(self, **kwargs):
        context = super(LeagueTransferView, self).get_context_data(**kwargs)
        context['players'] = Player.objects.filter(leagues=self.kwargs['pk']).exclude(teams=self.petitioner)
        return context

    def get_initial(self):
        initial = super(LeagueTransferView, self).get_initial()
        initial['league'] = self.kwargs['pk'] # add custom data to initial
        initial['petitioner'] = self.petitioner # add custom data to initial
        return initial

    def get_form(self, form_class=None):
        form = super(LeagueTransferView, self).get_form(form_class)
        # override the queryset
        form.fields['offered_player'].queryset = self.petitioner.players
        return form

    def get(self, request, *args, **kwargs):
        # only perform 1 query to get 'petitioner'
        self.petitioner = get_object_or_404(Team, user=self.request.user.profile, league=self.kwargs['pk'])
        return super(LeagueTransferView, self).get(request, *args, **kwargs)

关于python - Django 1.9 FormView永远不会到达get_context_data,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38774792/

10-11 08:53