1

This question might reveal a gaping hole in my knowledge of json queries, but I'm trying to get json data to display on a view with the following URL.

http://localhost:8000/structures/hydrants/json?id=%3D2/

Here's my URL regex:

url(r'^hydrants/json\\?id=(?P<hydrant_id>\d+)/$', views.hydrant_json, name='hydrant_json'),

and the view:

def hydrant_json(request, hydrant_id):
    hydrant = get_object_or_404(Hydrant, pk=hydrant_id)
    data = [hydrant.json()]
    return HttpResponse(json.dumps(data), content_type='application/json')

Obviously, the question mark is throwing it off, because if I make the regex

url(r'^hydrants/json/id=(?P<hydrant_id>\d+)/$', views.hydrant_json, name='hydrant_json'),

then the following URL will work:

http://localhost:8000/structures/hydrants/json/id%3D2/

Thanks in advance!

4

1 回答 1

1

如果您想将数据作为GET参数发送,您可以简单地执行以下操作:

url(r'^hydrants/json/$', views.hydrant_json, name='hydrant_json'),
url(r'^hydrants/json/(?P<hydrant_id>\d+)/$', views.hydrant_json, name='hydrant_json_with_key'),

和观点:

def hydrant_json(request, hydrant_id=None):
    if not hydrant_id:
       hydrant_id = request.GET.get('id')

    if not hydrant_id: #if hydrant_id is not received for some reason, throw 404. 
        raise Http404

    hydrant = get_object_or_404(Hydrant, pk=hydrant_id)
    data = [hydrant.json()]
    return HttpResponse(json.dumps(data), content_type='application/json')

在这里,您定义了发送hydrant_id到视图的灵活方式。

默认情况下,对于 GET 请求,request.GET将具有所有 get 参数 - 例如:?id=123

此外,如果您想hydrant_id作为 URL 的一部分发送,您可以这样做

http://localhost:8000/structures/hydrants/json/302/

请注意,3D2在正则表达式中永远不会匹配为 URL,因为您的 URL 正在寻找\d+仅是数字的 URL。

于 2013-06-13T17:06:27.327 回答