How import models in python script django ?

I have a tree like that :

cyberactu
├── models.py
├── __init__.py
├── Scraping
│   ├── __init__.py
│   ├── scrap.py

I’m in scrap.py and i want import a models from models.py.

I know I must add the cyberactu folder to my PYTHON PATH.
I do like that :

import sys
sys.path.append(path)

After that, if I try to import my models :

from models import MyClass

That raise a error :

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.

After view research this error mean i must link my Django settings to my file.
So I do that :

export DJANGO_SETTINGS_MODULE=website.settings

website is the name of my django project.

And that raise a other error:

ModuleNotFoundError: No module named 'website'

I have a empty init.py file in my cyberactu folder.

Thank you for helping me

Settings :

"""
Django settings for website project.

Generated by 'django-admin startproject' using Django 3.1.4.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['192.168.1.31','127.0.0.1']


# Application definition

INSTALLED_APPS = [
    'cyberactu.apps.CyberactuConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'website.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'website.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

Your “current directory” while in a module running in the Django environment is not the directory the file is located in, it’s your base directory for the entire project.

So assuming that cyberactu is a directory in the base directory, you only need to import from cyberactu.models.

edo@leanux:~/Desktop/website$ /bin/python3 /home/edo/Desktop/website/cyberactu/__init__.py
ok
Traceback (most recent call last):
  File "/home/edo/Desktop/website/cyberactu/__init__.py", line 2, in <module>
    from cyberactu.models import Cyberattaque
ModuleNotFoundError: No module named 'cyberactu'
edo@leanux:~/Desktop/website$ 

I don’t see how what you’ve posted has anything to do with importing modules from within a Django application. That’s not how you run a Django project.

What are you really trying to accomplish here?

I want import my models in my scrap.py

Why? What are you trying to do?

I want make database request inside my script.
I want have access to my models inside my script and add ou delete fews things in my database

Ah, ok. To rephrase it slightly, you want access to the Django ORM for a script you’re going to run from the command line.

What you’re looking for in this case is how to write Custom django-admin commands.

The reason for this is that Django models are not regular Python classes. There’s a lot of behind-the-scenes work being done to convert those models into the actual classes you use within your Django code. So, for you to have access to those models, your script needs to (effectively) start the Django environment and build those classes before your script can use them.

1 Like

Thx you boy that work !