For avoid SQL-injections Django documentation fully recommend use placeholders like that:

import mysql.connector

conn = mysql.connector.connect(host='localhost',user='user1',password='puser1',db='mm')
cursor = conn.cursor()
string1 = 'test1'
insert_query = """INSERT INTO items_basic_info (item_name) VALUES (%s)"""
cursor.execute(insert_query, (string1,))
conn.commit()

You have to pass tuple/list params in execute method as second argument. And all should be fine.

Answer from Jefferson Houp on Stack Overflow
🌐
Reddit
reddit.com › r/django › attributeerror: 'tuple' object has no attribute 'encode'
r/django on Reddit: AttributeError: 'tuple' object has no attribute 'encode'
August 13, 2020 -

I am creating a Contact page for my django project. forms.py has name, subject, sender and message. Here's the view:

And the form:

<form method="POST">

{%csrf_token%}

{{form.as_p}}

<button type="submit">Send</button>

</form>

After I click Send I get this error: AttributeError: 'tuple' object has no attribute 'encode' and I can't seem to figure out what's wrong despite checking other questions of the same type.

I am using google SMTP server, from this link following its instructions.

🌐
GitHub
github.com › Kludex › python-multipart › issues › 78
AttributeError: 'tuple' object has no attribute 'encode' · Issue #78 · Kludex/python-multipart
February 7, 2024 - Traceback (most recent call last): File ".\bug.py", line 3, in <module> parse_options_header( File "M:\Metrized\in-progress\metrized-cv\venv\lib\site-packages\multipart\multipart.py", line 118, in parse_options_header options[key.encode('latin-1')] = value.encode('latin-1') AttributeError: 'tuple' object has no attribute 'encode' With python-multipart==0.0.6, the output is: b'form-data' {b'name': b'parameters', b'filename': b'path\to\x0cile.png', b'filename*': b"utf-8''C:\Users\name\path\to3\file.png"} I believe a fix in parse_options_header could be (multpart.py:111-112): for param in params: key, value = param if isinstance(value, tuple): <---- These lines value = value[-1] <---- 👍React with 👍3jbvirt, bdenglish and violetanna ·
Author   lorenpike
🌐
Narkive
comp.lang.python.narkive.com › hROupzov › attributeerror-tuple-object-has-no-attribute-encode
AttributeError: 'tuple' object has no attribute 'encode'
Post by erikcw It raises this error: AttributeError: 'tuple' object has no attribute 'encode' What does? I imagine that this error comes from a call to a cursor object's execute method. In other words, I imagine that you may be cursor.execute(*sql) Not that there would be anything obviously wrong with that: you are keeping the string and its parameters separate, after all.
🌐
Reddit
reddit.com › r/learnpython › 'tuple' object has no attribute 'encode' for stmplib, two variables into one variable?
r/learnpython on Reddit: 'tuple' object has no attribute 'encode' for stmplib, two variables into one variable?
April 29, 2022 -

I am trying to call the function send_email with the variable message in it and combining it with a string contained in AlertSMSText and assigning it to text as well as html to HTMLEmailBody.

For some reason when I do text = AlertSMSText, message and it gives me the error AttributeError: 'tuple' object has no attribute 'encode' but if I do text = AlertSMSText + message and html = HTMLEmailBody + message it works fine except it ignores \n contained in the string that AlertSMSText has in it.

SendEmailAlert.py

def send_email(message):
  email_subject = JSONFileReader.SubjectEmail  
  sender_add = JSONFileReader.SenderEmail  
  receiver_add = JSONFileReader.ReceiverEmail  
  smsEmail_add = JSONFileReader.SMSEmailAdd  # SMS email
  AlertSMSText = JSONFileReader.AlertSMSText #Alert SMS Text message
  HTMLEmailBody = JSONFileReader.AlertHTMLEmailBody  #Alert Email message in HTML format
  password = JSONFileReader.gmailPass  # Password for the email you're sending from

  # Below is creating the SMTP server object by giving the SMPT server an address and port number
  smtp_server = smtplib.SMTP("smtp.gmail.com", 587)
  smtp_server.ehlo()  # setting the ESMTP protocol
  smtp_server.starttls()  # setting up to TLS connection
  smtp_server.ehlo()  # calling the ehlo() again as encryption happens on calling startttls()
  smtp_server.login(sender_add, password)  # logging into the senders email

  rcpt = smsEmail_add.split(",") + [receiver_add]  # Formats the recipients emails
  # Create message container - the correct MIME type is multipart/alternative.
  msg = MIMEMultipart('alternative')
  msg['Subject'] = email_subject
  msg['From'] = sender_add
  msg['To'] = receiver_add
  msg['Cc'] = smsEmail_add

  message.encode('utf-8')

  # Create the body of the message (a plain-text is for SMS and HTML is for email)
  text = AlertSMSText, message
  html = HTMLEmailBody, message


  # Record the MIME types of both parts - text/plain and text/html.
  part1 = MIMEText(text, 'plain')
  part2 = MIMEText(html, 'html')

  # Attach parts into message container.
  # According to RFC 2046, the last part of a multipart message, in this case
  # the HTML message, is best and preferred.
  msg.attach(part1)
  msg.attach(part2)

  smtp_server.sendmail(sender_add, rcpt, msg.as_string()) #Sends the email

  smtp_server.quit()  #Terminates the SMTP server

 ip= "10.1.50.2"
 send_email(ip + " is down.\n\nPlease reply with 'Ack' to pause alerts for 60 minutes")

In the JSON, the AlertSMSTextvariable equals to "Alert SMS Text": "This is an alert for your services \n\n IP: "

The output when text = AlertSMSText + message is all on one line and ignores newline \n:

This is an alert for your services IP:10.1.50.0 is down. Please reply with 'Ack' to pause alerts for 60 minutes

I want it to be:

This is an alert for your services

IP:10.1.50.0 is down. 

Please reply with 'Ack' to pause alerts for 60 minutes
🌐
LearnDataSci
learndatasci.com › solutions › python-attributeerror-tuple-object-has-no-attribute
Python AttributeError: 'tuple' object has no attribute – LearnDataSci
The error AttributeError: 'tuple' object has no attribute is caused when treating the values within a tuple as named attributes.
🌐
Post.Byes
post.bytes.com › home › forum › topic › python
AttributeError: 'tuple' object has no attribute 'encode' - Post.Byes
It raises this error: AttributeError: 'tuple' object has no attribute 'encode' > What does? I imagine that this error comes from a call to a cursor object's execute method.
Find elsewhere
🌐
GitHub
github.com › django › channels_redis › issues › 334
AttributeError: 'tuple' object has no attribute 'decode' when configuring using tuples · Issue #334 · django/channels_redis
October 21, 2022 - File "[..]lib/python3.10/site-... "/usr/lib/python3.10/urllib/parse.py", line 112, in <genexpr> return tuple(x.decode(encoding, errors) if x else '' for x in args) AttributeError: 'tuple' object has no attribute 'decode'...
Author   vanschelven
🌐
Kaggle
kaggle.com › questions-and-answers › 170399
'tuple' object has no attribute 'encode_plus'? BERT MODDEL
Checking your browser before accessing www.kaggle.com · Click here if you are not automatically redirected after 5 seconds
🌐
The Coding Forums
thecodingforums.com › archive › archive › python
AttributeError: 'tuple' object has no attribute 'encode' | Python | Coding Forums
April 5, 2007 - Here is the full error: (sorry) Traceback (most recent call last): File "/home/erik/Desktop/wa.py", line 178, in ? curHandler.walkData() File "/home/erik/Desktop/wa.py", line 91, in walkData sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test']) AttributeError: 'long' object has no attribute 'encode' sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test']) self.cursor.execute(sql) Now, I changed all ofth e %i/%d to %s, and changed self.cursor.execute(sql) to self.cursor.execute(*sql) and it seems to be working now!
🌐
GitHub
github.com › rpy2 › rpy2 › issues › 818
AttributeError: 'int' object has no attribute 'encode' when converting Tuple · Issue #818 · rpy2/rpy2
July 27, 2021 - def tuple_str(tpl): res = StrSexpVector(tpl) return res from rpy2.robjects.conversion import Converter seq_converter = Converter('sequence converter') seq_converter.py2rpy.register(tuple, tuple_str) from rpy2.robjects import default_converter conversion_rules = default_converter + seq_converter x = (1, 2, 'c') from rpy2.robjects.packages import importr base = importr('base') # error here: # NotImplementedError: Conversion 'py2rpy' not defined for objects of type '<class 'tuple'>' #res = base.paste(x, collapse="-") from rpy2.robjects import default_converter from rpy2.robjects.conversion import Converter, localconverter with localconverter(conversion_rules) as cv: res = base.paste(x, collapse="-")
Author   Unexas
🌐
GitHub
github.com › microsoft › azuredatastudio-postgresql › issues › 483
Error when executing table resulting function, having arrays: 'tuple' object has no attribute 'encode' · Issue #483 · microsoft/azuredatastudio-postgresql
October 4, 2023 - The full output: Started executing query at Line 3 Commands completed successfully Unhandled exception while executing query: 'tuple' object has no attribute 'encode' Total execution time: 00:00:00.180 Here is a simple reproduction: crea...
Author   n8allan
🌐
The Mail Archive
mail-archive.com › python-list@python.org › msg139061.html
Re: AttributeError: 'tuple' object has no attribute 'encode'
Here is the full error: (sorry) Traceback (most recent call last): File "/home/erik/Desktop/wa.py", line 178, in ? curHandler.walkData() File "/home/erik/Desktop/wa.py", line 91, in walkData sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test']) AttributeError: 'long' object has no attribute 'encode' sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test']) self.cursor.execute(sql) Now, I changed all ofth e %i/%d to %s, and changed self.cursor.execute(sql) to self.cursor.execute(*sql) and it seems to be working now! -- http://mail.python.org/mailman/listinfo/python-list ... Re: AttributeError: 'tuple' object has no attribute 'enco...
🌐
CopyProgramming
copyprogramming.com › howto › attributeerror-tuple-object-has-no-attribute-encode
AttributeError: 'tuple' object has no attribute 'encode' - Complete Guide & Solutions 2026 - Attributeerror: 'tuple' object has no attribute 'encode'
December 22, 2025 - The AttributeError: 'tuple' object has no attribute 'encode' is a common Python programming error that occurs when developers attempt to call the method on a tuple object instead of a string. In Python, the method is exclusively a string operation—tuples do not have this method, making the ...
🌐
Reddit
reddit.com › r/learnpython › tuple' object has no attribute 'decode'
r/learnpython on Reddit: tuple' object has no attribute 'decode'
December 12, 2020 -

im trying to pass number and operator to the server and pass back the answer using a UDP socket.

i get a 'tuple' object has no attribute 'decode' . on line 20 of the client. (print(answer.decode()).

if i take out the decode and input 5 + 5 it returns (b'10', ('127.0.0.1', 12456)).

can anyone help ve no idea. only been doing this for a week haha! code below

thanks alot.

client-

from socket import *
import socket
serverName = 'Localhost'
serverPort = 12456
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
number1 = input ('Input number1: ')
number2 = input ('Input number2: ')
operator = input ('Select an operator: (+ / * -) ')

clientSocket.sendto(number1.encode(),(serverName,serverPort))
clientSocket.sendto(number2.encode(),(serverName,serverPort))
clientSocket.sendto(operator.encode(),(serverName,serverPort))
answer= clientSocket.recvfrom(2048)
print (answer.decode())
clientSocket.close()

server -

from socket import *
import socket
serverName = 'Localhost'
serverPort = 12456
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
serverSocket.bind(('',12456))
print ('The server is connected')
while 1:
number1, clientAddress = serverSocket.recvfrom(2048)
number2, clientAddress = serverSocket.recvfrom(2048)

operator, clientAddress = serverSocket.recvfrom(2048)

if str(operator) == '+':
answer = int(number1.decode()) + int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
elif str(operator) == '-':
answer = int(number1.decode()) - int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
elif str(operator) == '/':
answer = int(number1.decode()) / int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
elif str(operator) == '*':
answer = int(number1.decode()) * int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
serverSocket.close()

Top answer
1 of 3
2
Check the doc for what socket.recvfrom() returns. Which is a tuple containing the text and the replying address. If you want to decode the data received (which is inside the tuple) then you need to get it out of the tuple first. Something like: answer = clientSocket.recvfrom(2048) (data, address) = answer print(data.decode()) You'll probably need to specify the encoding, perhaps "utf-8".
2 of 3
1
hey thanks guys, i have it working now. ill paste the code. thanks for the help server ------ import socket sPort = 12000 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # creat socket object s.bind(('',sPort)) # bind with localhost(127.0.0.1) and socket print ('server is Ready') # print that the server is ready to recieve the data while 1: message, clientAddress = s.recvfrom(2048) # recieve data from client message2, clientAddress = s.recvfrom(2048) message3, clientAddress = s.recvfrom(2048) number1  = (message.decode()) # decode data from client and assign it to an var number2 = (message2.decode()) number3 = (message3.decode()) number4 = int(number3) if (number4 == 1) : # if, elif to select the operation from user depending on the input from client modMessage1 = int(number1) + int(number2) #change the string recieved into a int modMessage = str(modMessage1) # change the int answer back to a str s.sendto(modMessage.encode(), clientAddress) #encode the string and pass it back to client # each section does the same as the first depending on the client input. elif (number4 == 2 ) : modMessage1 = int(number1) - int(number2) modMessage = str(modMessage1) s.sendto(modMessage.encode(), clientAddress) elif (number4 == 3 ) : modMessage1 = int(number1) * int(number2) modMessage = str(modMessage1) s.sendto(modMessage.encode(), clientAddress) elif (number4== 4 ) : modMessage1 = int(number1) / int(number2) modMessage = str(modMessage1) s.sendto(modMessage.encode(), clientAddress) client ------ import socket serverIP = "localhost" sPort = 12000 cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # creat socket object message = input('numer1\r\n') # read in first number in sum message2 = input('numebr2\r\n') # read in second number in sum message3 = input('1 to add, 2 for subtract, 3 for multiply, 4 for divide \r\n') # read in waht math operation user would like to do # send data to server make sure to encode it... cs.sendto(message.encode(), (serverIP, sPort)) cs.sendto(message2.encode(), (serverIP, sPort)) cs.sendto(message3.encode(), (serverIP, sPort)) # recieve modifed data from server and print it to terminal modMessgae = cs.recv(2048) print (modMessgae.decode()) # closesocket cs.close()
🌐
GitHub
github.com › pylakey › aiotdlib › issues › 1
'tuple' object has no attribute 'encode' · Issue #1 · pylakey/aiotdlib
July 17, 2021 - Traceback (most recent call last): File "/root/mm.py", line 26, in asyncio.run(main()) File "/usr/lib/python3.9/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/usr/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete return future.result() File "/root/mm.py", line 13, in main client = Client( File "/usr/local/lib/python3.9/dist-packages/aiotdlib/client.py", line 253, in init md5_hash.update((self.phone_number or self.bot_token).encode('utf-8')) AttributeError: 'tuple' object has no attribute 'encode' Reactions are currently unavailable ·
Author   morteza102030