2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. I'm going to try your second or third example. Because In the first example I don't know how to call different methods for different url using the same class... May be with a parameter in as_view(method='first_method')
Generics are intended to be used as in the second example (by inheritance) or even the third one (although I wouldn't do it, but it is allowed).
Thank you for your advice! So, it is better an independent class for each url? I would like to learn best practices...
IMHO I would not use the 3rd, perhaps. I don't like importing the model classes in the urls.py. But, again, is just my taste.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.