Django Class Based Generic Views URL Variable Pass

2019-03-18 08:49发布

问题:

Question is quite simple.

Let's say I have an URL config with line:

url(r'^models/(?P<model_group_id>[0-9]+)/(?P<page>\d+)/$', 'Group'),

And I want to access model_group_id variable inside

class Group(ListView)

View.

On simple views I would just change Group description to:

class Group(ListView, model_group_id):

And it would work. Now it says that model_group_id is not defined. So how to pass variables from url regex to class-based view?

回答1:

You can access positional arguments in self.args and name-based arguments in self.kwargs.

class Group(ListView): 

    def get_queryset(self):
        model_group_id=self.kwargs['model_group_id']
        ...

See the docs for more info.