简体   繁体   English

访问Django request.POST时输入错误

[英]Type error when accessing Django request.POST

I'm attempting to build an XML document out of request.POST data in a Django app:我正在尝试根据request.POST数据在 Django 应用程序中构建一个 XML 文档:

ElementTree.Element("occasion", text=request.POST["occasion"])

PyCharm is giving me an error on the text parameter saying Expected type 'str', got 'Type[QueryDict]' instead . PyCharm 在text参数上给我一个错误,说Expected type 'str', got 'Type[QueryDict]' instead I only bring up PyCharm because I know its type checker can be overzealous sometimes.我只提到 PyCharm 因为我知道它的类型检查器有时会过分热心。 However, I haven't been able to find anything about this issue specifically.但是,我无法具体找到有关此问题的任何信息。

Am I doing something wrong?难道我做错了什么? Or should I try to silence this error?还是我应该尝试消除此错误?

You are trying to take the type QueryDict and put it into an element that requires a string.您正在尝试采用 QueryDict 类型并将其放入需要字符串的元素中。

Here is the docs for QueryDict这是QueryDict的文档

If you take look at the documentation of this QueryDict type, then you can see that it basically is a dictionary.如果您查看此 QueryDict 类型的文档,那么您会发现它基本上是一个字典。

So to create XML elements you will have to do:因此,要创建 XML 个元素,您必须执行以下操作:

query_dict = request.POST["occasion"].dict() # For clarity
ele = Element('<main name>')
for key, val in :
    child = Element(key)
    child.text = val
    ele.append(child)

And there you have the XML element populated with the keys and values of the QueryDict.那里有 XML 元素,其中填充了 QueryDict 的键和值。

Assuming you're not posting anything unusual, like json, request.post['occasion'] should return a string, either the field 'occasion' or the last value of the list submitted with that name.假设您没有发布任何不寻常的内容,例如 json, request.post['occasion']应该返回一个字符串,即字段“occasion”或以该名称提交的列表的最后一个值。

There are apparently some httprequest related issues with pycharm, but the way to doublecheck if this is happening here would be to print out and/or type check request.post['occasion'] prior to that line to make sure of what it returns.显然 pycharm 存在一些与 httprequest 相关的问题,但是要仔细检查这里是否发生这种情况的方法是打印出来和/或在该行之前键入检查request.post['occasion']以确保它返回的内容。

Assigning request.post['occasion'] to a variable ahead of time might be a simple way to remove the pycharm error without turning off warnings, depending on your tolerance for extra code.提前将request.post['occasion']分配给变量可能是消除 pycharm 错误而不关闭警告的简单方法,具体取决于您对额外代码的容忍度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM