我用ListView制作了自己的组权限页面,以显示Django组列表以及pk到DetailView的链接,然后提供更改链接以使用UpdateView更改权限。

我想用pk将UpdateView的success_url设置为DetailView,该怎么做。

我的代码像:

views.py

class GroupCreation(PermissionRequiredMixin, CreateView):
    permission_required = 'add_group'
    model = Group
    form_class = GroupCreateModelForm
    success_url = reverse_lazy('account:group_list')
    template_name = 'accounts/groups/group_creation.html'


class GroupsListView(PermissionRequiredMixin, ListView):
    permission_required = 'view_group'
    allow_empty = True
    model = Group
    ordering = 'name'
    template_name = 'accounts/groups/groups_list.html'
    form = GroupCreateModelForm
    extra_context = {'form': form, }


class GroupDetailView(PermissionRequiredMixin, DetailView):
    permission_required = 'view_group'
    model = Group
    template_name = 'accounts/groups/group_detail.html'


class GroupUpdateView(PermissionRequiredMixin, UpdateView):
    permission_required = 'change_group'
    model = Group
    fields = ('permissions',)
    template_name = 'accounts/groups/group_update.html'
    success_url = reverse_lazy('account:group_detail')


urls.py

path('groups/', views.GroupsListView.as_view(), name='group_list'),
path('groups/<int:pk>/', views.GroupDetailView.as_view(), name='group_detail'),
path('groups/<int:pk>/change/', views.GroupUpdateView.as_view(), name='group_change'),
path('groups/create/', views.GroupCreation.as_view(), name='group_creation'),

最佳答案

您可以在get_success_url中使用UpdateView方法而不是success_url属性。这样,您可以访问编辑对象的pk

def get_success_url(self):
        return reverse_lazy('account:group_detail', kwargs={'pk': self.object.pk})

09-29 20:48