'Template' object has no attribute 'replace' - python

Whenever I run the code, the error is this:
'Template' object has no attribute 'replace'
Any help would be nice. Thanks!

The line
template = get_template("user/ticket_print.html")
returns a Template object and not a string containing the code you put in your template (which I think you expect). And the Template object does not have a method called replace() resulting in your error.
To access the string you can use
template.template.source
So I think in your case a slight change in your view could do the trick:
def ticket_print(request, cartitem_id):
item = get_object_or_404(CartItem, object_id=cartitem_id)
template = get_template("user/ticket_print.html")
value = template.template.source
html_result = render_template(value, {"itest": item.cart,},)
return html_to_pdf(html_result, name=f"Ticket_Print{item}")

Related

getting object has no attribute 'get' or object is not subscriptable when trying to access JSON response converted to DTO

I'm trying to access a JSON response, I've trying with get() method and I'm getting the "object has no attribute 'get'" error and when I tried it with [] I'm getting the "object is not subscriptable" error.
The response is valid, as I've printed it just before the get operation and all looks ok.
Did not had such problem parsing a response before.
def get_return_params_and_identifiers(return_params):
print("******** res start **********")
print(return_params)
print("******** res end **********")
return_parameters = return_params.get('return_parameters')
Here is part of a response:
******** res start **********
{'levels': None,
'return_parameters': [{'identifier_name': 'Premium',
'level': None,
'return_parameter_name_pk': 1258407,
'return_parameters_details': [{'base_parameter_name': 'Premium '
'Parameter',
'base_parameter_pk': 1149913,
'class_value': None,
....
....
Did anybody encountered such and have any idea what is happening.
EDIT:
Tried with json.loads() but the response is a DTO and not JSON anymore and thus getting the other error:
TypeError: the JSON object must be str, bytes or bytearray, not DTO
The DTO class is below:
class ReturnParametersContainerDTO(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'return_parameters': 'list[ReturnParameterDTO]',
'levels': 'LevelsDTO'
}
attribute_map = {
'return_parameters': 'returnParameters',
'levels': 'levels'
}
It clearly says that the items in the class are dictionary, but somehow it does not recognize it.
Ok, I solved the issue.
It was something in the implementation of the OpenApi's generated DTO class, that showed it as a dictionary (in to_str() method it called to_dict() and prints it as a dictionary) but in fact those were just properties, so used the method to_dict() (in swagger's generated class) to convert it to dictionary.
Now all works.

Python intermittently throws "AttributeError: 'NoneType' object has no attribute 'get'" on the same dictionary

I have a nested dictionary like so:
mail = {
'data': { 'from': {'text': '123#example.com'}}
# some other entries...
}
I'm trying to copy from value using following code:
data = mail.get('data')
new_dict['parse']['from'] = data.get('from').get('text')
The second line throws the exception:
AttributeError: 'NoneType' object has no attribute 'get'
The strange thing is, this only happens sometimes. If I add a print statement just before the second line like:
data = mail.get('data')
print(type(data.get('from')))
new_dict['parse']['from'] = data.get('from').get('text')
The error disappears and I get <class 'dict'> as expected. If I remove the print statement, it works sometimes and other times it throws the error. Nothing else changes in the code or data. The reason I'm using get() is to retrieve value safely in case the key is missing.
In the call data.get('from').get('text'), if data does not contain the key 'from', it will return None. None.get('text') raises then the exception you see, because a None object has no get method (of course).
The way around this is to pass in a better default-object than None (the default default-object), which has the get method. That would be an empty dictionary, {}:
data = mail.get('data')
new_dict['parse']['from'] = data.get('from', {}).get('text')

Python if no AttributeError

I have a small script that returns the title of a webpage
title = BeautifulSoup(urllib2.urlopen(URL)).title.string
But not all websites specify a <title> tag, in which case my script returns
AttributeError: 'NoneType' object has no attribute 'string'
Is there a way to have the title variable equal to the title if there is a title on the webpage?
I am tried
if BeautifulSoup(urllib2.urlopen(url)).title.string.strip():
print BeautifulSoup(urllib2.urlopen(url)).title.string.strip()
else:
print url
But it still raises the AttributeError error
try:
title = BeautifulSoup(urllib2.urlopen(URL)).title.string
except AttributeError:
title = url
You can use inbuilt function getattr to check whether the attribute exists and if not set a default value to it.
In your case it will be like
title = getattr(BeautifulSoup(urllib2.urlopen(URL)).title, 'string', 'default title')
Check documentation for getattr function - https://docs.python.org/2/library/functions.html#getattr

Getting Django object "is not JSON serializable"

I have a webservice that reads a JSON object and it was giving me unicodeEncodeError exception. After googling a little bit, I saw How can I convert a dict to a unicode JSON string?
(I followed other questions that were related to unicodeEncodeError but I was still getting AttributeError: 'dict' object has no attribute 'content')
I did what was mentioned in that particular question and now I am getting ..... is not JSON serializable
Can anyone tell me what do I have to do now?
Following is my code:
def someMethod()
some_data = request.data
json_string1 = json.dumps(some_data) #GETTING ERROR ON THIS LINE
json_string2 = get_string(json_string1)
archive = call.send_json(json_string2)
def get_string(value):
find_unicode = re.compile('\\\\u([\da-f]{4})')
def get_parsed_unicode(x):
return chr(int(x.group(1), 16))
return find_unicode.sub(get_parsed_unicode, str(value))
Thanks for the help !!
When you're passing the object to the method, use foo.serealize(true). Include JQUERY to use this.

unexpected attribute error in python object

I'm parsing objects returned by the suds client from a Web Services SOAP API
I have a list of attributeObjects, like
(defectStateAttributeValueDataObj){
attributeDefinitionId =
(attributeDefinitionIdDataObj){
name = "Comment"
}
attributeValueId =
(attributeValueIdDataObj){
name = "Owner changed because of default owner assignment specified in the component map"
}
}
and
(defectStateAttributeValueDataObj){
attributeDefinitionId =
(attributeDefinitionIdDataObj){
name = "OwnerName"
}
attributeValueId =
(attributeValueIdDataObj){
name = "Schmoe, Joe"
}
}
I use the following loop to extract key/value pairs:
for defect in myDefectsPage.mergedDefects :
print defect.cid,
for attribute in defect.defectStateAttributeValues:
print attribute
attr= attribute.attributeDefinitionId.name
val=attribute.attributeValueId.name
print attr,'=',val,
print ""
(The above objects are results of the print attribute command)
This will work as expected for EVERY attribute, except the one where attribute.attributeDefinitionId.name == "Comment"
for that one I get the
Traceback (most recent call last):
File , line 63, in
val=attribute.attributeValueId.name
AttributeError: 'Text' object has no attribute 'name'
which is strange, because if I use
val=attribute.attributeValueId #.name
it will print
Commment = (attributeValueIdDataObj){
name = "Owner changed because of default owner assignment specified in the component map"
}
So it looks like it IS an attributeValueIdDataObj and DOES have a name attribute.
I used the suds DEBUG logging and the XML return elements look exactly the same regardless of what the attribute.attributeDefinitionId.name is.
I have no idea how it changes into a 'Text' object when trying to access the name attribute
Any ideas?
On further examination (and printing out the type of the returned object when exception happened) this was a bug in the web services SOAP server.
When a Comment was empty, it returned an
<attributeValueId/>
tag,
instead of the proper
<attributeValueId>
<name/>
</attributeValueId>
object. so it resulted in sax.Text object instead of the suds.attributeValueIdDataObj object
So no python or suds mystery to solve.
Sorry for the false alarm...

Categories

Resources