dac777
dac777

Reputation: 101

Django class based views. Use same custom class for different url

I would like to know if it would be possible to create only a custom class for my views in django that could be valid for different urls.

For example:

#urls.py 
url(r'^$', CustomClass.as_view(), name='index'),
url(r'^other_url/(?P<example>[-\w]+)$', CustomClass.as_view(), name='other')

#views.py
CustomClass(View):
    # for / url
    def first_method(self, request):
        pass
    # for other_url/
    def second_method(self, request, example):
        pass

I have readed the documentation about class based views, but in the example only talks about a single url... https://docs.djangoproject.com/en/1.9/topics/class-based-views/intro/

So, I suppose I have to create a class for each url. But it would be possible use the same class with different methods for different url?

Upvotes: 2

Views: 898

Answers (1)

Luis Masuelli
Luis Masuelli

Reputation: 12333

You don't need to create different classes for different urls. Although it is pretty redundant to have the same class in different urls, you could do:

url(r'^$', CustomClass.as_view(), name='index'),
url(r'^other_url/(?P<example>[-\w]+)$', CustomClass.as_view(), name='other')

exactly what you're doing. There are some cases where you have a generic class you want to use (either generic from the generics module/package, or generic in the OOP sense). Say, an example:

url(r'^$', CustomBaseClass.as_view(), name='index'),
url(r'^other_url/(?P<example>[-\w]+)$', CustomChildClass.as_view(), name='other')

Or even the same class with only different configuration (regarding generic classes (descending from View): accepted named parameters depend on how are they defined in your class):

url(r'^$', AGenericClass.as_view(my_model=AModel), name='index'),
url(r'^other_url/(?P<example>[-\w]+)$', AGenericClass.as_view(my_model=Other), name='other')

Summary You have no restriction at all when using generic views, or passing any kind of callable at all, when using url.

Upvotes: 2

Related Questions