I am getting an Incorrect string value (Exception Value: Incorrect string value: '\xEA\xB0\x95\xED\x95\x98...' for column 'object_repr' at row 1) error while trying to save unicode string (Korean) in Django and MySQL.First problem I had was "Incorrect string value" error for each column in the database table. However, I figured this out by changing column collation and overall database character set.
The new error I am getting is related to unicode(self) method in models.py.My models.py is as the following:
from django.db import models
# Create your models here.
class User(models.Model):
full_name = models.CharField(max_length=60)
email = models.EmailField(unique=True)
password = models.CharField(max_length=128)
birthday = models.DateField(null=True, blank=True)
gender = models.PositiveIntegerField(null=True, blank=True)
location = models.CharField(max_length=60, null=True, blank=True)
captcha = models.CharField(max_length=60, null=True, blank=True)
register_date = models.DateTimeField()
lastLogin_date = models.DateTimeField(null=True)
num_logins = models.PositiveIntegerField()
def __unicode__(self):
return self.full_name
The error is generated when the__unicode__ function tries to output utf8 character...
Does anybody know how to fix this error?
In MySQL console execute
ALTER DATABASE django_db CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE django_admin_log MODIFY object_repr VARCHAR(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
For me it helps.
Try add one line on the first of this file like this:
#-*- encoding=UTF-8 -*-
I solved this problem by changing the file settings.py: Don´t use 'ENGINE': 'django.db.backends.mysql'.
Related
I am facing issue in saving string values in one of the fields of my domain
My Domain is
#Entity
#Table(name = "users")
class User {
#Id
#NotNull
Long id
#NotNull
String uuid
#NotNull
String firstName
}
I am pulling the data from my main mysql database and saving it into another database.
resultSet = statement.executeQuery(userQuery)
while (resultSet.next()) {
User user = new User()
user.id = resultSet.getLong("a.id")
user.uuid = resultSet.getString("a.uuid")
user.firstName = resultSet.getString("b.first_name") // exception occurs here
userRepository.save(user)
}
Some of my data is getting saved but when data from my main database contains user with
firstname = ऋषभ (Name in Hindi Language) then it throws exception.
Note - Only essential codes i mentioned here query execution database connection everything is running fine only facing issue in setting data in user.firstName only when my query result contains string with different language.
ALTER TABLE user MODIFY first_name VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
Currently i tried by modifying my property file to insert those special characters.But its inserting as a question mark instead of ₹ Symbol please find below changes.
spring.datasource.url=jdbc:mysql://localhost:3306/dbName?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false&useUnicode=true&character_set_server=utf8mb4
My Entity column definition
#Column(name = "question", columnDefinition = "TEXT")
private String question;
I tried by doing
1.change in column definition to "nvarchar" i got hibernate error.
2.In mysql changed column definition to ALTER TABLE table CHANGE column column VARCHAR(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
referred, to change mysql tables definitions enter link description here
In case of any modification or mistake help me.
Change the character encoding to utf8_general_ci by,
ALTER TABLE test_tb MODIFY COLUMN col VARCHAR(255)
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
And then,
insert into test_tb values("₹");
Look at #Nationalized annotation, it may help your problem Annotation Type Nationalized
#Nationalized
#Column(name = "question", columnDefinition = "TEXT")
private String question;
I have the following schema in django.
class function(models.Model):
func_id = models.IntegerField(primary_key=True)
func_name = models.CharField(max_length=30)
func_args = JSONField()
func_version = models.CharField(max_length=20)
func_desc = models.CharField(max_length=500)
user = models.ForeignKey(user_data,on_delete=models.CASCADE)
container_path = models.CharField(max_length=200)
class Meta:
db_table = 'function'
When I am trying to run the following query in postgres shell
INSERT INTO
function(func_id,func_name,func_args,func_version,func_desc,user_id,container_path)
VALUES (101,'Sum',{"input1":"a","input2":"b"},'1.7','blahblah',105,'/path');
I am getting below error:
ERROR: syntax error at or near "{"
LINE 1: ...nc_desc,user_id,container_path) VALUES (101,'Sum',{"input1":...
Any clue where I am going wrong?
Try enclosing your JSON in single quotes '{...}'. Even though JSONField supposedly works with python dictionaries, when doing raw SQL, postgresql won't understand that syntax.
I am facing issues with "makeflag" field which is bit(1) type in my database(MySQL). I have tried using booleanField and bit1booleanfield with below syntax. But i am getting error with both. when i try POST request with json data on this model,
I get error as
"Data too long for column" on passing 1 or 0 as value.
And when i give true or false as value, then i get 400 Bad Request.
Can someone please help me understand how can i post data using django and json for bit field (of mysql).
makeflag=models.BooleanField(db_column='MakeFlag', default=1)
makeflag=Bit1BooleanField()
My model is the next:
class Product(models.Model):
productid = models.AutoField(db_column='ProductID', primary_key=True)
name = models.CharField(db_column='Name', max_length=50)
productnumber = models.CharField(db_column='ProductNumber', max_length=25)
makeflag = models.TextField(db_column='MakeFlag', max_length=1)
color = models.CharField(db_column='Color', max_length=15, blank=True)
safetystocklevel = models.SmallIntegerField(db_column='SafetyStockLevel')
reorderpoint = models.SmallIntegerField(db_column='ReorderPoint')
standardcost = models.FloatField(db_column='StandardCost')
You probably need to use django-mysql for mysql specific functionality. Have a look docs for bit here
I have the following django code working on an sqlite database but for some unknown reason I get a syntax error if I change the backend to MySQL...does django's ORM treat filtering differently in MySQL?
def wsjson(request,imei):
wstations = WS.objects.annotate(latest_wslog_date=Max('wslog__date'),latest_wslog_time=Max('wslog__time'))
logs = WSLog.objects.filter(date__in=[b.latest_wslog_date for b in wstations],time__in=[b.latest_wslog_time for b in wstations],imei__exact=imei)
data = serializers.serialize('json',logs)
return HttpResponse(data,'application/javascript')
The code basically gets the latest logs from WSlog corresponding to each record in WS and serializes it to json.
Models are defined as:
class WS(models.Model):
name = models.CharField(max_length=20)
imei = models.CharField(max_length=15)
description = models.TextField()
def __unicode__(self):
return self.name
class WSLog(models.Model):
imei = models.CharField(max_length=15)
date = models.DateField()
time = models.TimeField()
data1 = models.DecimalField(max_digits=8,decimal_places=3)
data2 = models.DecimalField(max_digits=8,decimal_places=3)
WS = models.ForeignKey(WS)
def __unicode__(self):
return self.imei
Ok finally managed to fix it with code below
def wsjson(request,imei):
wstations = WS.objects.annotate(latest_wslog_date=Max('wslog__date'),latest_wslog_time=Max('wslog__time'))logs = WSLog.objects.filter(date__in=[a.latest_wslog_date for a in wstations],time__in=[b.latest_wslog_time for b in wstations],imei__exact=imei)
data = serializers.serialize('json',logs)
return HttpResponse(data,'application/javascript')
the weird part was the original code worked as expected in an ubuntu machine running MySql but failed in a windows machine (also running MySql)