Categories
Python Answers

How to pass additional parameters to the as_view method in a Python Django class-based view?

Spread the love

Sometimes, we want to pass additional parameters to the as_view method in a Python Django class-based view.

In this article, we’ll look at how to pass additional parameters to the as_view method in a Python Django class-based view.

How to pass additional parameters to the as_view method in a Python Django class-based view?

To pass additional parameters to the as_view method in a Python Django class-based view, we can use the slug property.

For instance, we write

from django.views.generic import DetailView

class MyView(DetailView):
    template_name = 'detail.html'
    model = MyModel
    slug = None

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

to create the MyView view class.

In the get_object view method, we get the slug value from self.slug.

Conclusion

To pass additional parameters to the as_view method in a Python Django class-based view, we can use the slug property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *