I'm trying to find a way on how to write one FormView that can handle different ModelForms.
My situation:
I have 6 models that have a common AbstractBaseClass with a custom ModelManager. I want to display them as ModelForms in a FormView that displays the form(s) and handles the POST data. They have the same methods.
My approach:
Abstract Base Class with a custom ModelManager that all models inherit from.
**models.py**
class AbstractBaseClass():
slug = models.CharField(max_length=20)
name = models.CharField(max_length=40)
objects = MyModelManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('some-name', kwargs=[str(self.name)])
class Meta:
abstract = True
class ChildClassOne(AbstractBaseClass):
city = models.CharField(...)
class ChildClassTwo(AbstractBaseClass):
city = models.CharField(...)
In forms.py I created the corresponding ModelForms ChildClassOneForm and ChildClassTwoForm with validation-methods.
My views.py is something like this:
**views.py**
class ChildClassOneView(FormView):
template_name = 'formulare/formular_detail.html'
form_class = ChildClassOneForm #here's the problem - it should work for other ModelForms, too
def post(self, request, *args, **kwargs)
form = self.form_class(request.POST)
if form.is_valid():
# do lots of different stuff with the data, send email, etc.
**I want to avoid:**
class ChildClassTwoView(FormView):
form_class = ChildClassTwoForm
# the rest is identical with ChildClassOneView
**urls.py**
path('forms/<str:slug>', ChildClassOneView.as_view(), name='some-name')
And here's my question:
How can I write a FormView that can be used for ChildClassOneForm AND ChildClassTwoForm? How can I pass more than one form to the FormView? Or in other words: How do I not repeat myself over and over again?
Thanks a lot for your ideas, it's much appreciated!