开发者

how to write re-usable views in django?

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开发者_StackOverflow中文版 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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜