Warning: this article is still a draft
Explaining the Django reusable apps in an agile way
- as a developer
- i want to easily plug the app into the project so that i can improve the productivity
- i want to customize and extend existing Django apps so that they fit the requirements
- some of the things that need customization:
- models
- e.g. make the app work with a different model class than the ones provided by the app
- e.g. create a custom model based on the one supplied by the app and add extra fields or modify the existing field definition
- forms
- e.g. the app should use a custom form
- e.g. a custom form which adds extra fields or change the definition of the existing ones
- template names
- success or redirect urls
- template variables (extra_context)
- models
1 James Bennett’s approach – the custom objects are passed as arguments to the views
- let the app’s views receive a number of parameters for which the view defined some defaults
- Django’s class based views support this strategy by default
- more on the subject:
- example
(APP/views.py)
def register(request, success_url=None,
form_class=RegistrationForm
template_name=’registration/registration_form.html’,
extra_context=None):
…
2 Use the settings to define the custom objects
- in settings.py, define the values for models/forms/etc which will be later used by the app
- it’s useful to prefix all the names required by a specific app, i.e. BLOGAPP_MODEL, BLOGAPP_FORM etc
- example
(settings.py)
MY_APP_MODEL = MyAppModel
(APP/views.py)
from django.conf import settings
from .models import AppModel
def register(request):
my_model = getattr(settings, ‘MY_APP_MODEL’, AppModel)
What the current approaches don’t offer
- an easy way to modify or extend the urls. The urlpatterns is just a list, it’s difficult to delete/edit/insert url definitions.
- models placed in models.py are used by Django in different db operations (i.e. syncdb).
One might want to ignore those models and let Django use customized/child Models.
- the Model and Form fields are not easy to alter
Ideas for a new solution
- make everything a class. Forms and Models are classes but the urls (or maybe the views) are not.
- move the Model definitions from models.py and allow the developer to use it’s own Models (i.e. though getters or factories)
- instead one can play with abstract models but without any concrete Models the app won’t work out of the box
- define the Form and Model fields inside a method so that the derived classes can modify the definitions
Resources
- ways to organize your app for reusability https://github.com/Natim/django-reusable-apps
- http://www.philipotoole.com/reusable-django-applications
- Django class based views https://docs.djangoproject.com/en/dev/topics/class-based-views/
- “eight spaces” – class based everything http://reinout.vanrees.org/weblog/2011/06/07/eight-spaces.html