Задать вопрос

Тел: +7 965 3737 888

495

Просмотров

5

Ответов

object-oriented generic views

<p>Here's an example of writing generic views in an object-oriented style, which allows for very fine-grained customization via subclassing.  The snippet includes generic create and update views which are backwards compatible with Django's versions.
</p>
<p>To use one of these generic views, it should be wrapped in a function that creates a new instance of the view object and calls it:
</p>
def create_object(request, *args, **kwargs):
    return CreateObjectView()(request, *args, **kwargs)
<p>If an instance of one of these views is placed directly in the URLconf without such a wrapper, it will not be thread-safe.
</p>

Вопрос полезен? Да0/Нет0
file_2971.py(7.8Кб)
None

Ответы (5):

Ответartur_mwaigaryan:29.10.2011
Ответ полезен? Да0/Нет0

quite efficient,cuts out boiler-plate code,@simon thanks alot for the insight:-)

Ответjamesgpearce:01.09.2009
Ответ полезен? Да0/Нет0

Oh - and now (v1.1) that the URL dispatcher include() can take sequences of patterns, the same class can even generate standardised URLs to tie to its own views.

Ответjamesgpearce:01.09.2009
Ответ полезен? Да0/Нет0

Why have separate classes for Create, Update etc - each with their own __call__?

If you just have one class (say, Views), you could have create, update methods etc on it.

The URL dispatcher can call a 'instance.verb' method just as well as it can __call__ a 'verb_instance' class.

Firstly, you only have to instantiate one class for the URL dispatcher, and secondly (as Simon does), the class properties are only provided once, regardless of how many view verbs you have.

Ответcarljm:29.08.2008
Ответ полезен? Да0/Нет0

Thanks Simon. You're totally right, of course. I briefly thought of doing that, but for some reason I had in mind as a goal to preserve backwards-compatibility with Django's generic views. Now I can't actually think of a single good reason to do that.

Ответsimon:29.08.2008
Ответ полезен? Да0/Нет0

I'm a big fan of this approach, but I don't think you're taking advantage of subclassing enough in this code. Instead of passing configuration parameters to the _call_ method I suggest having them as class properties, and then requiring that people subclass your generic views to customise them.

For example, your code could look like this:

class CreateObjectView(object):
    model = None
    form_class = None
    template_name = None
    ...

    def __call__(self, request):
        ...

Then your users would just have to do this:

class CreateArticleObject(CreateObjectView):
    model = Article