Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Class Based Generic Views URL Variable Passing

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?

like image 341
JackLeo Avatar asked Jan 19 '12 11:01

JackLeo


People also ask

What is a more efficient way to pass variables from template to view in Django?

Under normal usage the standard is to use URL (GET) variables when you are retrieving data from the server and to use Form (POST) variables when you want to manipulate (edit/delete) data on the server.

How do you call class-based views in Django?

A Django developer doesn't have a need to instantiate class-based views directly, so the constructor isn't something that you would interact with directly, but it is used by the as_view method to provide a chance when calling as_view to override attributes then. The dispatch method contains the actual view logic.

How do you use decorators in class-based view in Django?

To decorate every instance of a class-based view, you need to decorate the class definition itself. To do this you apply the decorator to the dispatch() method of the class. The decorators will process a request in the order they are passed to the decorator.


1 Answers

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.

like image 145
Alasdair Avatar answered Sep 29 '22 02:09

Alasdair