class ModelFormView(FormView): """ Use (?P[\-0-9]*) urls.py lookups to populate form instance """ lookups = ['id', ] def get_form_kwargs(self): """ Override to add instance """ self.get_instance() kwargs = {'initial': self.get_initial()} if self.request.method in ('POST', 'PUT'): kwargs.update({ 'instance': self.instance, 'data': self.request.POST, 'files': self.request.FILES, }) return kwargs def get_instance(self): """ Add in self.lookups list of attributes to search for instance """ model = self.get_form_class()._meta.model for lookup in self.lookups: look = self.kwargs.get(lookup, '') if look: try: self.instance = model.objects.get(*((lookup, look),)) self.pk = self.instance.pk return self.pk except ObjectDoesNotExist: self.instance = None return 0