I'm attempting to build an XML document out of request.POST
data in a Django app:
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
. I only bring up PyCharm because I know its type checker can be overzealous sometimes. 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?
CodePudding user response:
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 (or an error, if empty. Use request.POST.get('occasion') to avoid).
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.
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.
CodePudding user response:
You are trying to take the type QueryDict and put it into an element that requires a string.
Here is the docs for QueryDict
If you take look at the documentation of this QueryDict type, then you can see that it basically is a dictionary.
So to create XML elements you will have to do:
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.