0

Django reusable apps

Posted October 31st, 2012 in Python by Florentin

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)

1 James Bennett’s approach – the custom objects are passed as arguments to the views

 

(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

Leave a Reply