Home > Back-end >  Redirect back to original post after updateview
Redirect back to original post after updateview

Time:11-03

I have an update view that is working as expected. The only issue is that I cant figure out how to redirect back to the post that was being updated after submission. I believe I am on the right track with get_success_url but I cant get it working

view

class UpdateBuildLog(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = BuildLog
form_class = BuildLogupdateForm
template = 'blog/buildlog_update.html'

def get_object(self):
    return BuildLog.objects.get(pk=self.kwargs["pkz"])

def form_valid(self, form):
    form.instance.author = self.request.user
    return super().form_valid(form)

def get_success_url(self):
    pk = self.kwargs["pkz"]
    return reverse("build-log-view", kwargs={"pkz": pk})
        
def test_func(self):
    post = self.get_object()
    if self.request.user.id == post.author_id:
        return True
    return False    

urls:

path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'),
path('post/<int:pk>/build-log/<int:pkz>/delete/', views.BuildLogDelete, name='build-log-delete'), 
path('post/<int:pk>/build-log/<int:pkz>/update/', UpdateBuildLog.as_view(), name='build-log-update'),

Error:

NoReverseMatch at /post/127/build-log/75/update/
Reverse for 'build-log-update' with keyword arguments '{'pkz': 75}' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9] )/build\\-log/(?P<pkz>[0-9] )/update/$']

CodePudding user response:

You need both pk and pkz in your reverse:

def get_success_url(self):
    pkz = self.kwargs["pkz"]
    pk = self.kwargs["pk"]
    return reverse("build-log-view", kwargs={"pkz": pkz, "pk": pk})
  • Related