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:
- Assign a value to a field behind the scenes
- 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;
- Does it matter if I use self.object.sheme.pk or self.kwargs.get(‘pk’)? Both works as expected.
- 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.