user3214546
user3214546

Reputation: 6831

How can i use custom function in class based views

I have this view

class UserView(GenericAPIView):
    def get(self, request, format=None, **kwargs):
        pass

    def post(self, request, format=None, **kwargs):
        pass

This works fine with this url

url(r'^user$', UserView.as_view(),name='user'),

but i want to have custom url

def  custom():
      pass

I want that

url(r'^user/custom/$', UserView.as_view(custom),name='user'),

How can i do that

Upvotes: 4

Views: 3562

Answers (1)

Paulo Pessoa
Paulo Pessoa

Reputation: 2569

You can't do this.

from django.conf.urls import url
from django.views.generic import TemplateView

urlpatterns = [
    url(r'^about/', TemplateView.as_view(template_name="about.html")),
]

Any arguments passed to as_view() will override attributes set on the class. In this example, we set template_name on the TemplateView. A similar overriding pattern can be used for the url attribute on RedirectView.

If you want a 'custom' url, Use the Functions Based views

Urls

url(r'^user/custom/$', custom, name='user'),

Views

def custom(request):
     # your custom logic
     # return something

Edit 1* If you want pass parameters to the CBV.

class View(DetailView):
    template_name = 'template.html'
    model = MyModel
    # custom parameters
    custom = None

    def get_object(self, queryset=None):
        return queryset.get(custom=self.custom)

Url

url(r'^about/', MyView.as_view(custom='custom_param')),

Upvotes: 3

Related Questions