什么是一种更有效的方法来创建一个没有虚拟形式的无场形式。形式?

问题描述 投票:0回答:1

我正在尝试实现一个简单地呈现数据的表单,并为用户提供“接受”或“拒绝”的选择。我通过覆盖get_context_data()方法发送我想要显示的数据,我在模板上有两个<input type="submit">

这是观点:

class FriendResponseView(LoginRequiredMixin, FormView):
    form_class = FriendResponseForm
    template_name = 'user_profile/friend_response.html'
    success_url = '/'

    def get_context_data(self, **kwargs):
        context = super(FriendResponseView, self).get_context_data(**kwargs)
        context['respond_to_user'] = self.kwargs.get('username')
        responding_profile = Profile.objects.get(
            user__username=self.request.user)
        requesting_profile = Profile.objects.get(
            user__username=self.kwargs['username'])

        friend_object = Friend.objects.get(requester=requesting_profile, accepter=responding_profile)
        context['accepter_asks'] = friend_object.requester_asks
        return context

    def form_valid(self, form):
        super(PairResponseView, self).form_valid(form)
        if 'accept' in self.request.POST:
            # do something
        else:
            return redirect('/')  

因为表单不接受任何输入或选择,我有这个虚拟形式:

class FriendResponseForm(forms.Form):
    pass

必须有一种更有效的Django方法来实现相同的结果。我该怎么办呢?

django django-forms django-templates django-views
1个回答
1
投票

最好的方法是根本不使用FormView,而是使用基本的TemplateView。然后定义post来做提交逻辑。

class FriendResponseView(LoginRequiredMixin, TemplateView):
    template_name = 'user_profile/friend_response.html'

    def get_context_data(self, **kwargs):
        ...

    def post(self, request):
        if 'accept' in self.request.POST:
            # do something
        else:
            return redirect('/')  
© www.soinside.com 2019 - 2024. All rights reserved.