更正Django URL配置以读取JSON

时间:2012-08-04 17:23:13

标签: django json url rest

我正在尝试学习一些REST。我已经为现有的Django应用添加了几个视图,尝试使用REST和JSON做各种事情。我能够让我的应用程序通过多个视图发送请求的数据,但我似乎无法接受JSON作为URL的一部分。

我创建了一个如下所示的视图:

def restCreateEvent(request,key,jsonString):     errors = checkKey(key)

if errors == None:
    eventJson = json.loads(jsonString)

    eventInfo = eventJson['event']
    title = eventInfo['title']
    description = eventInfo['description']

    locationInfo = eventInfo['location']

    place = locationInfo['place_name']
    street = locationInfo['street_address']
    city = locationInfo['city']
    state = locationInfo['state']
    zip = locationInfo['zip']

    event = models.Event()
    event.title = title
    event.description = description
    event.street_address = street
    event.place_name = place
    event.city = city
    event.state = state
    event.zip = zip
    event.save()

else:
    return errors

但是,我似乎无法获得正确的URL,这就是我现在所拥有的:

(r'^events/rest/create/(?P<key>\d+)/(?P<jsonString>.+)', 'events.views.restCreateEvent')

当我尝试访问以下网址时,Django调试抱怨我的网址都没有匹配。

http://127.0.0.1:8000/events/rest/33456/create/{"title":"test","description":"this is a    test","location":{"place_name":"somewhere","street_address":"123   main","city":"pittsburgh","state":"pa","zip":"11111"}}

现在视图从未被调用过,所以很明显我的网址是错误的。那么,我的方法在这里完全错了吗?如果不是我如何修复网址?

1 个答案:

答案 0 :(得分:1)

你为什么要这样做?像任何有效负载一样,发送JSON的方法是将其放在POST数据中,而不是URL。