views:

78

answers:

2

These are the techniques that I use regularly to make my views reusable:

  • take the template_name as an argument with a default
  • take an optional extra_context which defaults to empty {}
    • right before the template is rendered the context is updated with the extra_context
    • for further re-usability, call any callable in extra_context.values()
  • whenever the view deals with a queryset, there is a queryset argument with a default
  • whenever the view needs a particular object from the ORM, it attempts to fetch it using any "id" parameter in several ways (e.g. as a slug, as a database id) (this may be a bad practice...)

First, should I add anything to my list? Should I remove anything from my list?

The items accommodates a large number of cases. However, whenever an app extends a model of another in some way (e.g. adding a field or changing the behavior in some way) I end up writing my own views and only reusing the model. Is this normal?

Edit/answering my own question partially:

  • signals: the view should emit a signal when it starts and one before it returns the response
A: 

I would think that doing all of those puts a large burden on your urlconf to get everything right. Perhaps making a function that takes all that and hardcoding your views to be a glorified wrapper around said function would be better.

Ignacio Vazquez-Abrams
if all the arguments to me view have good, sensible defaults, to account for the common use-cases, how would that burden the urlconf?
rz
A: 

whenever the view needs a particular object from the ORM, it attempts to fetch it using any "id" parameter in several ways (e.g. as a slug, as a database id) (this may be a bad practice...)

So... why not just expect a model instance to be passed in as a parameter? Or a QuerySet from which you will take element 0? Then you can combine it with the QuerySet case, and maybe roll it into get_object_or_404.

My suggestion is to look at how Django's generic views are written. They're solving the same general class of problems you are. You seem most of the way there, except for the last part.

Mike D.
Good idea about the generic views, I'll try that. The reason to not expect a model instance as a parameter is that it violates MVC. The urlconf would have to supply the object from the models, which is the job of the view, not the urlconf.
rz