Django: AttributeError: view object has no attribute 'kwargs'

Django: AttributeError: view object has no attribute 'kwargs'

我正在构建一个视图,我正在从 url 传递一个 uuid。但是,当我尝试访问 kwarg 时,出现 "AttributeError: view object has no attribute 'kwargs'" 错误。

在我的模板中,我传递了一个 UUID:

create/97261b96-23b8-4915-8da3-a90b7a0bdc8e/

URL:

re_path(
    r"^create/(?P<uuid>[-\w]+)/$",
    views.DetailCreateView.as_view(),
    name="detail_create"),

视图:

class DetailCreateView(SetHeadlineMixin, LoginRequiredMixin, InlineFormSetView):
    inline_model = Detail
    headline = "Create a Detail"
    form_class = DetailForm
    success_message = "Detail Added"
    template_name = "details/detail_create.html"

    def get_object(self, **kwargs):
        return Post.objects.get_subclass(uuid=self.kwargs.get('uuid'))

    def __init__(self, *args, **kwargs):
        super(DetailCreateView, self).__init__(*args, **kwargs)
        self.object = self.get_object()
        self.model = self.object.__class__()

有关正在发生的事情的上下文 -

问题

知道为什么我无法访问在 URL 路径中发送的 kwargs 吗?

尝试使用self.request.query_params.get('uuid')

as_view 方法中 kwargsargs 属性在 __init__ 方法之后分配给视图。因此,当您在 __init__ 中调用 get_object 时,它会引发错误,因为 self.kwargs 尚未分配。要修复此错误,您可以移动

self.object = self.get_object()
self.model = self.object.__class__()

__init__get_object:

class DetailCreateView(SetHeadlineMixin, LoginRequiredMixin, InlineFormSetView):
    inline_model = Detail
    headline = "Create a Detail"
    form_class = DetailForm
    extra = 10
    success_message = "Detail Added"
    template_name = "details/detail_create.html"

    def get_object(self, **kwargs):
        self.object = Post.objects.get_subclass(uuid=self.kwargs.get('uuid'))
        self.model = self.object.__class__()
        return self.object

    def __init__(self, *args, **kwargs):
        super(DetailCreateView, self).__init__(*args, **kwargs)