djangoformsetinline-formset

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


I am building a view that I am passing in a uuid from the url. However when I try to access the kwarg, I get a "AttributeError: view object has no attribute 'kwargs'" error.

In my template, I am passing a UUID:

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

The URL:

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

The View:

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

For context on what is happening -

Question

Any ideas why I can't access the kwargs which is being sent in the URL path?


Solution

  • In as_view method kwargs and args attributes are assigned to the view after __init__ method. So when you call get_object inside __init__ it raises the error since self.kwargs is not assigned yet. To fix this error you can move

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

    from __init__ to 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)