我有一个包含两个表单的详细视图,这里我只提供其中一个表单的代码。表单位于用户详细视图上的模态中,我需要将客户端重定向到表单所在的详细视图。在post方法中,request.GET['user']
返回用户id,因此我拥有实现这一点所需的一切。我已经尝试过reverse
和redirect
,我想由于代码错误,没有任何效果。
我应该提供get_success_url()
吗?我认为这会引起一些问题,因为我只能从post方法获得用户id。
class UserDetailView(LoginRequiredMixin, DetailView):
model = TbUser
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['entrance_rights_form'] = TbPeopleEntranceRightForm(
user=self.object, initial={'user': self.object})
return context
class TbPeopleEntranceRightFormView(FormView):
form_class = TbPeopleEntranceRightForm
template_name = 'users/create_entrance_permission_modal.html'
def post(self, request, *args, **kwargs):
print(request.POST['user']) # returns user id
entrance_rights_form = self.form_class(
user=None, data=request.POST)
terminal_permissions_form = TbTerminalPermissionForm(user=None)
if entrance_rights_form.is_valid():
entrance_rights_form.save()
return redirect('user-detail', args=(request.POST['user'],))
else:
return redirect('users-list')
urlpatterns = [
path('users-list/', UsersListView.as_view(), name='users-list'),
path('user-detail/<str:pk>/',
UserDetailView.as_view(), name='user-detail'),
path('tb-entrance-right-form/submit',
TbPeopleEntranceRightFormView.as_view(), name='tb-entrance-right-form'),
]
您不需要将参数中的用户id作为带有重定向的元组传递。
这应该有效:
if entrance_rights_form.is_valid():
entrance_rights_form.save()
user_id = request.POST['user'] # i suppose this returns user id as you mentioned
return redirect('user-detail', user_id)
编辑:您没有在post方法中呈现模板。
def post(self, request, *args, **kwargs):
print(request.POST['user']) # returns user id
entrance_rights_form = self.form_class(
user=None, data=request.POST)
terminal_permissions_form = TbTerminalPermissionForm(user=None)
if entrance_rights_form.is_valid():
entrance_rights_form.save()
return redirect('user-detail', request.POST['user'])
else:
return redirect('users-list')
return render(request, self.template_name, {'form': entrance_rights_form})