Prometheus
Prometheus

Reputation: 33655

Get parameters slugs from the URL

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?

Upvotes: 1

Views: 1794

Answers (3)

Michał Bielawski
Michał Bielawski

Reputation: 76

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.

Upvotes: 1

arulmr
arulmr

Reputation: 8846

Try this

self.kwargs['company']
self.kwargs['program']

Upvotes: 2

Priyank Patel
Priyank Patel

Reputation: 3535

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']

Upvotes: 2

Related Questions