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
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.
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 .
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.
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.
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With