Search code examples
pythondjangodjango-formsdjango-urlsdjango-url-reverse

Django Forms - redirect after save


I have a detail view with 2 forms and here I provide code for only one of them. The form is located in a modal on user detailed view and I need to redirect the client to that detail view in which the form is. In the post method the request.GET['user'] returns the user id so I have everything needed to achieve this. I have tried the reverse and redirect, nothing worked I guess because of wrong code.

Should I provide a get_success_url() to do that? I think it will cause some problems because I can get user id only from post method.

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'),
]


Solution

  • You don't need to pass the user id in the args as a tuple with redirect.

    This should work:

    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)
    

    EDIT: you are not rendering the template inside the post method.

    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})