【问题标题】:Django: AttributeError: view object has no attribute 'kwargs'Django:AttributeError:视图对象没有属性'kwargs'
【发布时间】:2018-08-20 14:57:56
【问题描述】:

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

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

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

网址:

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__()

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

  • Post 是一个模型,它是一个 InheritanceManager,其他模型(产品和变体)继承自该模型。
  • “产品”和“变体”两种模型都有很多细节字段。
  • 创建详细信息后,我会将其添加到 Product 对象或 Variation 对象中。
  • 要为 InlineFormSetView 设置模型,我尝试使用 UUID 来查询对象并根据我尝试为其创建详细信息的对象的类动态设置它。

问题

任何想法为什么我无法访问在 URL 路径中发送的 kwargs?

【问题讨论】:

    标签: django formset inline-formset


    【解决方案1】:

    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)
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-09
        • 2023-03-03
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-15
        • 2021-03-30
        相关资源
        最近更新 更多