仅在我不使用GET方法时才接收信息

时间:2018-02-19 01:55:23

标签: python django

在我的项目中,我正在显示特定ID的JSON对话,ID将作为URL中的参数传递。

def conversationview(request, convo_identification):
    data = InputInfo.objects.all()
    conversation_identification = request.GET.get('convo_identification')
    #conversation_id = {'conversation_id': []}
    header = {'conversation_id': '', 'messages': []}
    entry = {}
    output = {}

    for i in data:
        if str(i.conversation_id) == conversation_identification:
            header['conversation_id'] = i.conversation_id
            entry = {}
            entry['sender'] = i.name
            entry['message_body'] = i.message_body
            entry['date_created'] = str(i.created)
            header.get('messages').append(entry)
            output = json.dumps(header)
    return HttpResponse(output) 

URLs.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^message/', sendMessage.as_view(), name='message'),
    url(r'^conversations/(?P<convo_identification>\d+)', views.conversationview, name='conversationview'),
]

conversation_identification = request.GET.get('convo_identification')不起作用(屏幕上没有显示任何内容),但当我将其更改为conversation_identification = convo_identification时,它将显示该ID的信息。我没有任何HTML,因为我不需要它。但我想知道为什么我不能使用request.GET或request.get.GET()?有关系吗?通过查看终端我知道有一个GET请求。

2 个答案:

答案 0 :(得分:1)

Django正在将 convo_identification 变量解析为URL参数,而不是请求对象的一部分。当urls.py引用views.py时,该值被设置为参数。

当您尝试从request.GET字典中获取 convo_identification 时,它不存在,因此get方法无法返回任何内容。这不会导致错误,但会静默设置空值。

要验证您的request.GET字典中没有与 convo_identification 匹配的密钥,您可以打印request.GET字典的内容:

print(request.GET)

此外,由于变量在视图引用时被初始化,因此除非您只是更改名称,否则不需要重新声明变量。

答案 1 :(得分:1)

您将直接从convo_identification获取Scope of the function,您无需访问request对象即可访问网址参数。
所以,更改行
conversation_identification = request.GET.get('convo_identification') conversation_identification = convo_identification将解决您的问题:)