【问题标题】:How to access url part in python django?如何在 python django 中访问 url 部分?
【发布时间】:2015-04-15 22:24:07
【问题描述】:

我正在使用 django 开发 API。我想通过以下方式访问我的资源: {base_url}/employee/{emp_id}

这里emp_id 不是GET 参数。如何在我的视图中访问此参数?有什么标准的方法可以在不手动解析 URL 的情况下访问它?

【问题讨论】:

  • 您阅读过URL dispatcher 上的文档吗?这是一个很好的开始,可以详细解释这一点。
  • 这个链接很好!谢谢!这是否意味着我需要编写不同的函数来处理不同的请求?
  • 一般都是这样处理的,除非处理不同的请求本质上是一样的,只是少了几个参数。将不同的 url 模式映射到单个视图函数很容易。

标签: django django-views


【解决方案1】:

根据您是使用基于类的视图还是使用标准视图函数,方法会有所不同。

对于基于类的视图,取决于您愿意执行的操作(ListView、DetailView、...),通常您不需要解析 url,只需在 urls.py 中指定参数的名称或直接在类定义中的参数名称。

基于类的视图

urls.py

from mysite.employee.views import EmployeeView

urlpatterns = patterns('',
    ...
    url(r'^employee/(?P<pk>[\d]+)/$', EmployeeView.as_view(), name='employee-detail'),
    ...
)

员工/views.py

class EmployeeView(DetailView):
    model = YourEmployeeModel
    template_name = 'employee/detail.html'

当您需要导入DetailView时,请阅读knbk向您指出的文档

就这么简单,您将根据给定的pk 参数获得您的员工。如果不存在会抛出 404 错误。


基于函数的视图中以类似的方式完成:

urls.py

from mysite.employee.views import EmployeeView

urlpatterns = patterns('',
    ...
    url(r'^employee/(?P<pk>[\d]+)/$', 'mysite.employee.views.employee_detail', name='employee-detail'),
    ...
)

员工/views.py

from django.shortcuts import get_object_or_404

def employee_detail(request, pk):
""" the name of the argument in the function is the 
    name of the regex group in the urls.py
    here: 'pk'
"""
    employee = get_object_or_404(YourEmployeeModel, pk=pk)

    # here you can replace this by anything
    return HttpResponse(employee)

希望对你有帮助

【讨论】:

  • 这能回答你的问题吗?如果可以,请标记已解决
猜你喜欢
  • 2010-12-03
  • 2014-05-03
  • 2013-03-06
  • 2021-08-28
  • 2013-10-30
  • 1970-01-01
  • 2019-08-26
  • 2018-10-05
  • 2023-04-03
相关资源
最近更新 更多