简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM