2

I am learning django version 1.11.4 through tutorial on the official documentation. I am using python 3.6.5 and mysql8 for database. I also use mysql.connector.django to connect to mysql database. I tried to do the first Django app, part 2.

This is the link of the example I used

everything works fine except when I run the this command:

Question.objects.all()

I got the following error:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 226, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __iter__
    self._fetch_all()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 1118, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 62, in __iter__
    for row in compiler.results_iter(results):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 839, in results_iter
    for rows in results:
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1284, in cursor_iter
    sentinel):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1283, in <lambda>
    for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)),
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/utils.py", line 101, in inner
    return func(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/cursor_cext.py", line 510, in fetchmany
    rows.extend(self._cnx.get_rows(size))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 275, in get_rows
    row[i])
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/conversion.py", line 205, in to_python
    return self._cache_field_types[vtype[1]](value, vtype)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/django/base.py", line 119, in _DATETIME_to_python
    dt = MySQLConverter._DATETIME_to_python(self, value)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/conversion.py", line 506, in _DATETIME_to_python
    (date_, time_) = value.split(b' ')
AttributeError: 'datetime.datetime' object has no attribute 'split'

the code used in the models file :

import datetime

from django.db import models

from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - 
        datetime.timedelta(days=1)

    def __str__(self):
        return self.question_text



class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
    return self.choice_text

the database setting:

DATABASES = {
    'default': {
        'NAME': 'mysite',
        'ENGINE': 'mysql.connector.django',
        'USER': 'root',
        'PASSWORD': '********',
        'OPTIONS': {
          'autocommit': True,
        },
    }
}

any clue or help to fix this error will be appreciated.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
Saleh
  • 284
  • 1
  • 3
  • 15
  • 1
    The error seems similar to [this bug report](https://bugs.mysql.com/bug.php?id=90541). The Django docs warn that [MySQL connector may not support the most recent releases of Django](https://docs.djangoproject.com/en/2.0/ref/databases/#id9). You could try using the recommended package `mysqlclient` instead. – Alasdair Apr 23 '18 at 09:39
  • I spent about 2 days to install mysqlclient on mac with no success. that is why I switch to mysql connector. I tried every possible solution to fix different errors with no luck . – Saleh Apr 23 '18 at 09:44
  • this is the error that I could not fix when ever I tried to install mysqlclient – Saleh Apr 23 '18 at 09:46
  • Command "/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/private/var/folders/cg/ttg6lfr17pb005f63_0y7b6r0000gn/T/pip-install-qwt4df54/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/cg/ttg6lfr17pb005f63_0y7b6r0000gn/T/pip-record-apcxyrd9/install-record.txt --single-version-externally-managed --compile" – Saleh Apr 23 '18 at 09:47
  • failed with error code 1 in /private/var/folders/cg/ttg6lfr17pb005f63_0y7b6r0000gn/T/pip-install-qwt4df54/mysqlclient/ – Saleh Apr 23 '18 at 09:47
  • Since the bug report mentions MySQL 8 which was recently released, you could try an earlier version of MySQL. [PyMySQL](https://github.com/PyMySQL/PyMySQL) might be another option, although it's not officially supported. – Alasdair Apr 23 '18 at 09:52

4 Answers4

4

I struggled for few hours to set up my Django project with python3 using MySQL DB on MacOS. I was not able to install either mysqlclient and MySQL-Python by pip3 in a virtual environment created with virtualenv

error stacktrace was: something wrong due to configparser in python3

Jans-MacBook-Pro:~ jan$ /Library/Frameworks/Python.framework/Versions/3.3/bin/pip-3.3 install MySQL-python
Downloading/unpacking MySQL-python
Running setup.py egg_info for package MySQL-python
Traceback (most recent call last):
  File "<string>", line 16, in <module>
  File "/var/folders/lf/myf7bjr57_jg7_5c4014bh640000gn/T/pip-build/MySQL-python/setup.py", line 14, in <module>
    from setup_posix import get_config
  File "./setup_posix.py", line 2, in <module>
    from ConfigParser import SafeConfigParser
ImportError: No module named 'ConfigParser'
Complete output from command python setup.py egg_info:
Traceback (most recent call last):

File "<string>", line 16, in <module>

File "/var/folders/lf/myf7bjr57_jg7_5c4014bh640000gn/T/pip-build/MySQL-python/setup.py", line 14, in <module>

from setup_posix import get_config

File "./setup_posix.py", line 2, in <module>

from ConfigParser import SafeConfigParser

ImportError: No module named 'ConfigParser'

----------------------------------------
Command python setup.py egg_info failed with error code 1 in /var/folders/lf/myf7bjr57_jg7_5c4014bh640000gn/T/pip-build/MySQL-python
Storing complete log in /Users/jan/.pip/pip.log
Jans-MacBook-Pro:~ jan$ 

Now the SOLUTION which worked for me was

1) installing mysql with brew again

brew install mysql

2) upgrading mysql with brew to latest version (if required)

brew upgrade mysql

3) installing mysqlclient now with pip3 (installing globally without virtualenv)

pip3 install mysqlclient

4) now access virtualenv and instal the mysqlclient in it, it will install fine without any error for configparser

Aishwary Dhare
  • 509
  • 1
  • 6
  • 18
2

As can be seen in the bug report posted by @Alasdair, the solution is:

Set use_pure=True in DATABASES['default']['OPTIONS'].

Adelin
  • 7,809
  • 5
  • 37
  • 65
  • thank you @adelin, this was very helpful in my case. For anyone else who might need this, I was running into an issue fetching a model with a DateTimeField with Django 1.11.14, mysql-connector-python 8.0.11, and mysql 5.7. This resolved the issue. – mozillalives Jul 27 '18 at 03:34
1

I too went through this pain yesterday or 2 days ago and was able to get it running with the mysqlclient-1.3.12. I'm going from memory here so bear with me, I tried a lot of things but eventually I got it to work.

I installed mysql8 and mysql8connector from the mysql web site as you did but got no love. After much searching and many trial and errors I found an answer somewhere which I can't find my way back to but I ended up doing:

brew install mysql pip install mysqlclient

I know that you already have mysql installed but brew install mysql seems to add client libraries that are used to compile the mysqlclient connector. Then my database in my settings file looks like:

DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'polls', 'USER': 'myuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'charset': 'utf8mb4', 'autocommit': True, }, } }

Note the ENGINE is different. I can replicate your exact error if I change my ENGINE to mysql.connector.django.

However, using django.db.backends.mysql I still get the following warning:

lib/python3.6/site-packages/django/db/backends/mysql/base.py:71: Warning: (3719, "'utf8' is currently an alias for the character set UTF8MB3, which will be replaced by UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous."

which I can't figure out, but as it is only a warning the Django tutorial seems to be working fine.

Let me know if this helps or if you have other questions and I'll do my best to help.

Lehrian
  • 347
  • 1
  • 2
  • 9
1

This is mysql-connector-python data conversion issue. You can get around this by setting the database options parameter with use_pure=true. This issue is not fixed in the current version 8.0.11,8.0.12, and 8.0.13.

"OPTIONS":{
 "use_pure":True
}

This is just a temporary solution. Refer here for more information: https://bugs.mysql.com/bug.php?id=90541

MUNGAI NJOROGE
  • 1,144
  • 1
  • 12
  • 25