[Django]-Django 1.3 – Correct way to define optional parameters for a class based view

4πŸ‘

βœ…

The url arguments are stored in self.args and self.kwargs. There are some examples in the dynamic filtering section of the generic class based views docs.

You could pass default arguments by including extra options in your url pattern, or just set a default in your view when you fetch the value from self.kwargs.

my_value = self.kwargs.get('key', 'default_value')
πŸ‘€Alasdair

1πŸ‘

For those who happen to be looking at this question, here is what I end up doing in 1.3. It is pretty much the same as how i used to do it in 1.1 (except more verbose). (i.e. as described in the link in my question)

for e.g. relevant lines in urls.py might look like

...
# pass a default value of page = 1 for optional parameter page
url(r'^obj/list$', ObjListView.as_view(), {'page': 1}, name='obj_list'),
url(r'^obj/list/page(?P<page>[0-9]+)$', ObjListView.as_view(), name='obj_list'),
...
# both new and edit use the same class, but edit obviously needs an id for the object.
# i should probably just be using pk but whatever.
url(r'^obj/new$', ObjEditView.as_view(), name='obj_edit'),
url(r'^obj/edit/(?P<obj_id>[0-9]+)/$', ObjEditView.as_view(), name='obj_edit'), 

in the case of ObjEditView class above, we may have something like this

class ObjEditView(UpdateView):
    ...
    form_class = ObjForm
    model=Obj
    ...

    # this puts our obj in self.object
    def get_object(self):
        # if the obj exists, intialize our variables with values from the obj instance
        # if it is a new obj, intialize accordingly
        try:
            obj = Obj.objects.get(id = self.kwargs['obj_id'])       
        except (KeyError, ObjectDoesNotExist):
            obj = Obj()

        return obj

As a corollary to my question to Alasdair in the comments above, the order of execution for the various functions inside the classes generally corresponds to the order they are in the documentation. i.e. in UpdateView get_object() comes before get_initial()

πŸ‘€w–

0πŸ‘

Somewhat related to this issue. I’ve been looking how to grab url parameters using class based views to add some extra context. You can do something like this:

url(r'^param1/(?P<param1>\d+)/param2/(?P<param2>\d+)/$', ClassDetailView.as_view())

and then in your view:

def get_context_data(self, **kwargs):
    context = super(ClassDetailView, self).get_context_data(**kwargs)
    context['param1'] = Model.objects.get(pk=self.kwargs['param1'])
    context['param2'] = Model.objects.get(pk=self.kwargs['param2'])
    return context

Then in your templates you’ll have {{ param1 }} and {{ param2 }} objects available to you.

I’m new to this so feel free to hack on this if there is a better way to do it.

πŸ‘€Andrew

Leave a comment