我正在构建一个视图,该视图是我从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路径中发送的kwarg?
答案 0 :(得分:4)
在kwargs
方法之后,在as_view
方法中将args
和__init__
属性分配给视图。因此,当您在get_object
内部调用__init__
时,会引发错误。由于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)
答案 1 :(得分:0)
尝试使用self.request.query_params.get('uuid')