Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django class view: __init__

I want to get <Model> value from a URL, and use it as an __init__ parameter in my class.

urls.py
url(r'^(?P<Model>\w+)/foo/$', views.foo.as_view(), name='foo_class'),

views.py
class foo(CreateView):
    def __init__(self, **kwargs): 
        text = kwargs['Model']         # This is not working
        text = kwargs.get('Model')     # Neither this
        Bar(text)
        ...

Clearly, I'm missing something, or my understanding of URL <> class view is wrong.

like image 736
Kotey Avatar asked Oct 06 '17 05:10

Kotey


1 Answers

You should override dispatch method for such use cases.

class Foo(CreateView):

    def dispatch(self, request, *args, **kwargs):
        # do something extra here ...
        return super(Foo, self).dispatch(request, *args, **kwargs)

For your specific scenario, however, you can directly access self.kwargs as generic views automatically assign them as an instance variable on the view instance.

like image 82
hspandher Avatar answered Sep 19 '22 15:09

hspandher