使用GET方法时无法接收信息,只有当我不使用时才能。

2024-06-02 09:39:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的项目中,我为某个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) 

网址.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请求正在发出


Tags: nameidurlmessageoutputgetrequestheader
2条回答

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

当您试图从request.get字典中获取conva\u标识时,它不存在,因此get方法无法返回任何内容。这不会导致错误,但会自动设置空值

要验证您的request.GET dictionary中没有匹配车队标识的密钥,可以打印request.GET dictionary的内容:

print(request.GET)

另外,由于变量是在视图是引用时初始化的,所以实际上不需要重新声明变量,除非您只是更改名称

您将直接从Scope of the function获取convo_identification,您不需要访问request对象来访问url参数。
因此,将行
^{>更改为conversation_identification = convo_identification将解决您的问题:)

相关问题 更多 >