6

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.

11
  • there is no request if you use .as_view(). 'name 'request' is not defined' Commented Oct 6, 2017 at 6:17
  • 2
    You need to show more details. Where do you want to use these parameters? Usually in Django views overriding __init__ is the wrong thing to do. Commented Oct 6, 2017 at 6:36
  • I want to use generic view CreateView to add objects to model, and pass model name by URL. ex. To add object to Foo1: xxx/Foo1/foo, add object to Bar2: xxx/Bar2/foo. I have class ready, it works with hardcoded inputs, but I can't get it going with kwargs. Commented Oct 6, 2017 at 7:21
  • 1
    But where is that code? You'd probably need to put it in get_form_class. Commented Oct 6, 2017 at 8:40
  • 1
    For the third time. You do not need to, and must not, override __init__. Put that code in get_form_class. Commented Oct 6, 2017 at 10:58

1 Answer 1

17

You should override dispatch method for such use cases.

class Foo(CreateView):

    def dispatch(self, request, *args, **kwargs):
        # do something extra here ...
        return super().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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.