0

In my Django project I have an app called 'catalog', here's the model in models.py:

from django.db import models

    class Catalog(models.Model):
    
        brand = models.CharField(max_length=255)
        supplier = models.CharField(max_length=255)
        catalog_code = models.CharField(max_length=255, null=True, blank=True)
        collection = models.CharField(max_length=255)
        season = models.CharField(max_length=255)
        size_group_code = models.CharField(max_length=2)
        currency = models.CharField(max_length=3)
        target_area = models.CharField(max_length=255)

I want to create one Catalog object but I don't want to do it using the admin panel or a form, so in the same app 'catalog' I've created tools.py which is just a script, it reads a csv file and create an istance of Catalog().

from catalog.models import Catalog


def create_catalog(file):
    with open(file, 'r') as f:
          f = f.readlines()
          catalog = Catalog(# all my keyword args)
          catalog.save()

I don't know if the script is fine but it's not important, my problem is when I try to run tools.py froom my IDE I get this error:

raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

I tried to run it from the shell with:

exec(open('catalog/tools.py').read())

but nothing happens and no traceback.

So how can I run a Python script inside of a Django project that creates objs in my DB? I'm already aware of: How to execute a Python script from the Django shell? and this. but no solution worked.

Brocante
  • 21
  • 1
  • Are you running your script with python or with django? If you want to run a script in django context you should be creating a commnad. – rigons99 Nov 10 '20 at 14:47
  • 1
    the second answer of "How to execute a Python script from the Django shell? " is the best.it works,try it – kiviak Nov 10 '20 at 14:50
  • I'm running the script with python, I'm new to Django and not aware of commands, I'll go search the docs – Brocante Nov 10 '20 at 14:50

1 Answers1

0

The best solution would be to make a management command that can be run by typing

python manage.py <insert_name_here>

You can read more about it here:

https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/

brukidm
  • 49
  • 5