Rafael Ortega
Rafael Ortega

Reputation: 454

Django 1.9 get kwargs in class based view

I was wondering if there is a way to get the kwargs directly in a class based view. I know this can be done in functions inside the class, but I'm having problems when I try this:

views.py

class EmployeesUpdateStudies(UpdateView):
    form_class = form_ES
    model = EmployeePersonal
    template_name = 'employeesControll/employees_studies_update_form.html'
    success_url = reverse('employee-details',  kwargs={'pk': kwargs.get('pk')})

My url is the following

url(r'^employees/detalles/(?P<pk>[0-9]+)/$', login_required(views.EmployeeDetails.as_view()), name='employee-details')

Upvotes: 0

Views: 849

Answers (2)

Alasdair
Alasdair

Reputation: 308939

You can't use kwargs in success_url, because when Django loads the class when the server starts, it doesn't have access to the request. Override the get_success_url method instead.

def get_success_url(self) 
    return reverse('employee-details', kwargs={'pk': self.kwargs['pk']})

Upvotes: 2

Moses Koledoye
Moses Koledoye

Reputation: 78554

Alasdair's answer solves your problem. You can however define a get_absolute_url method for your EmployeePersonal model which will act as the success_url for your view:

You don’t even need to provide a success_url for CreateView or UpdateView - they will use get_absolute_url() on the model object if available.

You'll use self.id in the get_absolute_url method for the model objects primary key.


Reference:

Model Forms

Upvotes: 3

Related Questions