开发者

Django - use generic views or not?

I was going through quick poll tutorial on the Django site, and the last topic is introduction of generic views. A convenient way to bypass the need of creation of custom views for every URL pattern.

This is the main idea as far as I understand:

1) Request -> URL patterns -> View -> Te开发者_开发问答mplate

or

2) Request -> URL patterns (Generic View) [-> optional Template]

2 seems to require less code, it's only two steps as opposed to four, but on the downside you're sticking more stuff into URL patterns, there's more automagic going on, and your views are now defined in two places.

I really like the idea of having URL Patterns just that - patterns, and not adding in additional boilerplate. I also like the idea of having all Views explicitly defined, even the simple ones, so that later I know where to find them all without going back and forth through files. Plus we all know that any automagic is harder to customise than something you build from scratch (at least from Django scratch).

Am I missing something? Am I doing a big mistake that will haunt me later of I don't use generic views at all?


The intention of Generic Views is to reduce boilerplate code when you repeatedly use similar code in several views. You should really use it just for that. Basically, just because django allows something you are doing generically you shouldn't do it, particularly not when your code becomes not to your like.

If you are using django-1.3's Class Based Views, instead of passing many variables to the function in urls.py, you can override respective methods of interest, which provides the best of both worlds. - Less code, and more control.


Whether to use generic views or not is your prerogative. It won't cause you any trouble, although you might find yourself coding repetitious view logic. You might consider using wrapped/subclassed generic views in your views.py (frequently you'll want to customize them anyways), which would keep the boilerplate out of your urls.py and all the views in the same place.


In django 1.2 I use generic views but inside a "normal" view , not in urls, like :

#views.py
import generic_views

def my_generic_list(request):
    qs = Something.objects.filter(some arguments)
    return generic.object_list(queryset = qs, ... other stuff, usually extra_context)

this way (imo) the view is very simple yet can become a "real one" in case of changes, while the urls.py remain clean

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜