Did you install mysqlclient? Yes: environment problem?

I was able to makemigrations and migrate models.py, but when I tried to use a python script to add data, it told me one of my fields needed a default. After correcting that, django balks at trying to makemigrations, telling me it couldn’t find django, then mysqlclient. Thinking the environments might have become confused, I replaced the django env and reloaded Django, connector, and client successfully; but the problem remains.

Traceback (most recent call last):
  File "C:\AIO_Html\sandbox\manage.py", line 22, in <module>
    main()
  File "C:\AIO_Html\sandbox\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\core\management\__init__.py", line 416, in execute
    django.setup()
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\apps\registry.py", line 116, in populate
    app_config.import_models()
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\apps\config.py", line 269, in import_models
    self.models_module = import_module(models_module_name)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python312\Lib\importlib\__init__.py", line 90, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 995, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\contrib\auth\models.py", line 5, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\contrib\auth\base_user.py", line 40, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\db\models\base.py", line 143, in __new__
    new_class.add_to_class("_meta", Options(meta, app_label))
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\db\models\base.py", line 371, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\db\models\options.py", line 231, in contribute_to_class
    self.db_table, connection.ops.max_name_length()
                   ^^^^^^^^^^^^^^
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\utils\connection.py", line 15, in __getattr__
    return getattr(self._connections[self._alias], item)
                   ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\utils\connection.py", line 62, in __getitem__
    conn = self.create_connection(alias)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\db\utils.py", line 193, in create_connection
    backend = load_backend(db["ENGINE"])
              ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\db\utils.py", line 113, in load_backend
    return import_module("%s.base" % backend_name)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python312\Lib\importlib\__init__.py", line 90, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\AIO_Html\dj_env\Lib\site-packages\django\db\backends\mysql\base.py", line 18, in <module>
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?
(dj_env) PS C:\AIO_Html\sandbox> 
from django.db import models

# Create your models here.
class Images(models.Model):
    accession_code = models.CharField(max_length=50, unique=True, db_index=True)
    date_year = models.CharField(max_length=4, db_default="0000")
    date_month = models.CharField(max_length=4, db_default="00")
    date_day = models.CharField(max_length=4, db_default="00")
    caption = models.CharField(max_length=50, db_default="Enter caption", blank=True)
    other_info = models.TextField(db_default="Add Comments", help_text="Add Comments")
    raw_file_exists = models.BooleanField(db_default=False)
    envelope_id = models.CharField(
        max_length=50,
        db_default='physical print code link for later',
        blank=True,
        help_text="To link to Lisa's physical prints some day"
    )  
    photographers_id = models.IntegerField
    orientation_vertical = models.BooleanField(db_default=False)
    access_level = models.SmallIntegerField(db_default=0)
    # access_level: 1 = high, 2= = medium (maintenance), 3 = public (read-only data)

    def __str__(self):
        return self.accession_code 

        
class Photographers(models.Model):
    fname = models.CharField(max_length=50)
    lname = models.CharField(max_length=50)
    email = models.EmailField
    address_street = models.CharField(max_length=50)
    address_city = models.CharField(max_length=50)
    address_state = models.CharField(max_length=50)
    address_zip = models.CharField(max_length=50)
    last_updated = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        full_name = self.lname + ", " + self.fname
        return self.full_name  


class Keywords(models.Model):
    keyword = models.CharField(max_length=50)
    Images_image_id = models.ManyToManyField(Images)

    def __str__(self):
        return self.keyword

Have you installed pip install mysqlclient ?

Yes, in fact I had accessed the database via that django program just a few minutes prior. The I shifted to python to bulk load keywords from a CSV file, but when I tried to bulk load image accession numbers the same way, I got an error statement saying I needed a default value for one of the other fields in the image table.

I returned to django and added a default value in models.py, at which point the program refused to make the connection to the DB. I have no idea why.

I seem to get myself to a certain point with django; then everything goes south, and I have to start all over and rebuild the program from the start. I am running out of unique names for the program so it doesn’t get confused and start grabbing things from the former versions.

Can you describe more clearly what you’re doing when you say you “shifted to python” and “returned to Django”?

I have a script that loads bulk data from a CSV file into my database. Ultimately there may be thousands of images that we need to track. Below is the keyword import script; the image script is almost identical. The Django program is intended to be the front end for the MySQL DB for maintenance and for public web access.

# This works 9/8/24

import csv
import mysql.connector
# Connect to MySQL
cnx = mysql.connector.connect(
	user='root', 
	password='************', 
	host='127.0.0.1', 
	database='sandbox')
cursor = cnx.cursor()
# Open CSV file and insert to MySQL
with open('Data/keywordList240805.csv', mode='r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        cursor.execute("INSERT INTO main_keywords (keyword) VALUES (%s)", row)
# Commit and close
cnx.commit()
cursor.close()
cnx.close()

Yes but:

It sounds like something you’re doing is messing up the virtual environment in which you’re running Django. But it’s hard to diagnose without knowing exactly what you’re doing when you stop using Django, start running a separate Python script, and then start using a now-broken Django again.

That is what I suspect. Although the Python program deals only with the DB (and has no explicit env folder), when I returned to the Django program and changed the models file only enough to add a default value to the field that “needed” it, the program no longer could connect to the DB.

I think the db_default should be default for setting the default values in all your models.

anaefta,

I tried that when I first entered the models, but that did not work (along with a few other things I thought would).

Yesterday I rebuilt the DB from scratch (up to the point where it failed) and managed to re-establish the connection. So far, so good.

Thanks to all for your help.