Best practices for using kwargs in Generic Editing Views

Hi, I’m doing a learning project, and while trying implement some Generic Editing Views for my forms, I wanted to figure out a way to access the ‘id’ from the URL to do two things:

  1. Assign a value to a field behind the scenes
  2. Establish the success URL.
    After referring to several similar questions here, I managed to make the form work but in doing so I came across multiple ways to use the kwargs, and now I’m not sure if I’m using the proper/ standard way to handle things. The relevant code is this:

‘’’
urlpatterns += [
path(‘scheme/uuid:pk/buldings/add/’, comp_view.BuildingCreateView.as_view(), name=‘create-building’),
]

class BuildingCreateView(PermissionRequiredMixin, CreateView):
model = Building
form_class = BuildingCreateForm
permission_required = ‘components.add_building’

# def get_form_kwargs(self):
#     kwargs = super(BuildingCreateView, self).get_form_kwargs()
#     kwargs['pk'] = self.kwargs.get('pk')
#     return super().get_form_kwargs()

def get_success_url(self) -> str:
    # return reverse_lazy('schemes:scheme-detail', args=[self.object.scheme.pk])
    return reverse_lazy('schemes:scheme-detail', args=[self.kwargs.get('pk')])

def form_valid(self, form):
    # form.instance.scheme = WaterScheme.objects.get(pk=self.kwargs['pk'])
    form.instance.scheme = WaterScheme.objects.get(pk=self.kwargs.get('pk'))
    form.instance.updated_by = self.request.user
    return super().form_valid(form)

‘’’
So my questions are;

  1. Does it matter if I use self.object.sheme.pk or self.kwargs.get(‘pk’)? Both works as expected.
  2. The commented out get_form_kwargs(self) method didn’t seems to do anything but it worked anyways… Is is simply that it is not necessary in this specific case?

Any help is much appreciated.

It depends upon where you’re using it in the sequence of events.

self.kwargs['pk'] will work everywhere in the view.

self.object.scheme.pk will only work after the object has been created.

That function, as written, does nothing (as you noted). It would never be useful in its current form.

Thank you very much, Ken! Going to stick with the self.kwargs[‘pk’] for the future then :smiley: