First of all, I'm pretty new to Python & Django, so it might a simple question. Now, I have a model like this:
models.py
class Base(models.Model):
class Meta:
abstract = True
# base properties
class X(Base):
# extra props
class Y(Base):
# extra props
Then I want to have a view for X and one for Y which will basically do the same, for example:
views.py
class BaseView(object):
template_name = "app/view.html"
Type = None
def __init__(self, type):
self.Type = type
def get_context_data(self, **kwargs):
context = super(BaseView, self).get_context_data(**kwargs)
context['data'] = get_object_or_404(self.Type, pk=kwargs["id"])
return context
class XView(BaseView, generic.TemplateView):
def __init__(self):
BaseView.__init__(self, X)
class YView(BaseView, generic.TemplateView):
def __init__(self):
BaseView.__init__(self, Y)
urls.py
urlpatterns = [
url(r'^xxxx/(?P<id>[0-9]+)$', views.XView.as_view(), name="view_x"),
url(r'^yyyy/(?P<id>[0-9]+)$', views.YView.as_view(), name="view_y"),
]
Like this, I will have to repeat probably all (or most of) the forms, views, etc. Is there anyway to avoid such duplication? The different between X and Y are just a few fields that are perfectly generated by django in the forms.
I need to differentiate the model based on the URL, example.com/X/ or example.com/Y/ being all the rest more or less the same.
FYI, using Python 3, Django 1.9.