Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter to django as_view function

I have one url that passes a parameter through the as_view function:

url(
    r'^$',
    ChangeListView.as_view(
        columns=('username', 'email')
    ),
    name="user-list"
),

When i try to access the columns attribute in the view it returns None instead of the tuple that i have passed through the url

class ChangeListView(generic.ListView):
    columns = None

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        print(self.columns)
        # Returns None instead of tuple
        return context
like image 514
kostas trichas Avatar asked Mar 22 '18 10:03

kostas trichas


People also ask

How do I pass url parameters in Django?

Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.

What does As_view do in Django?

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 .

What is CBV in Django?

Django has two types of views; function-based views (FBVs), and class-based views (CBVs). Django originally started out with only FBVs, but then added CBVs as a way to templatize functionality so that you didn't have to write boilerplate (i.e. the same code) code over and over again.

What is TemplateView Django?

Django provides several class based generic views to accomplish common tasks. The simplest among them is TemplateView. It Renders a given template, with the context containing parameters captured in the URL. TemplateView should be used when you want to present some information on an HTML page.


1 Answers

You don't have anything that actually sets self.columns from the data you pass in.

But this isn't the right way to do it. Instead, pass it as an extra option, and access it from the kwargs.

url(
    r'^$',
    ChangeListView.as_view(),
    {'columns': ('username', 'email')}
    name="user-list"
),

...

print(self.kwargs['columns'])
like image 92
Daniel Roseman Avatar answered Oct 16 '22 12:10

Daniel Roseman