1

I'm trying to get two parameters out of the URL to add to my context.

This is the URL:

  url(r'^company/(?P<company>[\w\-\_]+)/?/(?P<program>[\w\-\_]+)/?$', RegistrationView.as_view(),
                       name='test'), 

The view:

class RegistrationView(RegistrationMixin, BaseCreateView):
    form_class = AppUserIntroducerCreateForm
    template_name = "registration/register_introducer.html"
    slug_field = 'company'



    def get_context_data(self, *args, **kwargs):
        context = super(RegistrationIntroducerView, self).get_context_data(**kwargs)
        print(self.get_slug_field())
        context['company'] = ??????
        context['program'] = ??????
        return context

I have tried everything to get the values self.company, kwargs['company'] etc, what I'm I doing wrong here?

Prometheus
  • 32,405
  • 54
  • 166
  • 302
  • 1
    self.kwargs is the way to go. An example is here: http://stackoverflow.com/questions/6629426/django-class-based-generic-views-and-authentication – mawimawi Apr 01 '14 at 10:06

3 Answers3

2

Here is SO reference for you .

context = super(RegistrationView, self).get_context_data(**kwargs)
print(self.get_slug_field())
context['company'] = self.kwargs['company']
context['program'] = self.kwargs['program']
Community
  • 1
  • 1
Priyank Patel
  • 3,495
  • 20
  • 20
2

Try this

self.kwargs['company']
self.kwargs['program']
arulmr
  • 8,620
  • 9
  • 54
  • 69
1

The as_view class method of the base class (View) is a closure around a pretty simple view function that accepts the arguments defined in urls.py. It then assigns them as a dictionary to self.kwargs attribute of the view class. Therefore what you need to do in order to access this data is:

self.kwargs['company']

Also, if you inherited your RegistrationView from CreateView instead of BaseCreateView, you'd get SingleObjectTemplateResponseMixin mixed in with your view and the slug_field (along with model or queryset) would be used by get_object method to fetch the desired company. Furthermore, the context variable company containing the Company instance would be already set for you and you would not have to set it yourself.