我试图实现一个简单呈现数据的表单,并为用户提供选择"接受"或"拒绝"。我通过覆盖get_context_data()
方法发送了我想要显示的数据,模板上有两个<input type="submit">
&#39}。
以下是观点:
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方法来实现相同的结果。我该怎么做呢?
答案 0 :(得分: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('/')