Django - 从URL获取参数

时间:2014-07-02 09:46:59

标签: python django django-views django-urls

我将URL中的参数传递给我的视图,如下所示:

127.0.0.1:8000/cars/?model_number=13375

并且这样:

class GetCarDetails(View):
    def get(self, *args, **kwargs):
        model_number = "";
        if request.GET.get('model_number'):
            model_number = request.GET.get('model_number')

但是我现在想要传递它:

127.0.0.1:8000/cars/13375/

我希望Django能够处理13375类型号

1 个答案:

答案 0 :(得分:2)

您需要在网址

中定义它
url(r'^cars/(?P<pk>[0-9]+)/$', views.GetCarDetails.as_view(), name="getcardetails"),

在你的意见中:

class GetCarDetails(View):

    ...

    def get_context_data(self, **kwargs):
        context = super(GetCarDetails, self).get_context_data(**kwargs)
        context["model_number"] = self.kwargs['pk'];
        return context

正如@Anentropic在评论中所说,更详细的信息here