I'm working with a Django FormView. I've been looking all over but I can't find an example for how to load an object if PK is provided.
Currently I just set the form_class to a ModelView form. I want to use this view to either load an empty object if no pk is given, or load the form with the specific object if a pk is provided via the url.
I don't know if I need need to load it in get_form_kwargs or get_form or somewhere else. I'd really just like a tutorial on how to do it that way. I do not want to use CreateView or UpdateView, only FormView.
Can anyone point me in the right direction?
I would do it in get_form_kwargs
. That should return a dictionary of kwargs to pass into the form. For example if the pk
is in the url:
class MyAwesomeFormView(FormView):
def get_form_kwargs(self):
form_kwargs = super(MyAwesomeFormView, self).get_form_kwargs()
if 'pk' in self.kwargs:
form_kwargs['instance'] = models.AwesomeModel.objects.get(pk=int(self.kwargs['pk']))
return form_kwargs