简体   繁体   English

Django 1.9在基于类的视图中获取kwargs

[英]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. 我想知道是否有一种方法可以在基于类的视图中直接获取kwarg。 I know this can be done in functions inside the class, but I'm having problems when I try this: 我知道这可以在类中的函数中完成,但是当我尝试这样做时遇到了问题:

views.py 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. Alasdair的答案解决了您的问题。 You can however define a get_absolute_url method for your EmployeePersonal model which will act as the success_url for your view: 但是,您可以为EmployeePersonal模型定义一个get_absolute_url方法,该方法将充当视图的success_url

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. 你甚至都不需要提供success_urlCreateViewUpdateView -他们会用get_absolute_url()如果可用的模型对象。

You'll use self.id in the get_absolute_url method for the model objects primary key. 您将在get_absolute_url方法self.id用于模型对象的主键。


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. 您不能在success_url使用kwargs ,因为当Django在服务器启动时加载该类时,它无权访问该请求。 Override the get_success_url method instead. 改写get_success_url方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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