2019-11-08
How to use functions from a custom module in Python Django shell
stackoverflow
Question

I have a python file called my_functions.py in which I have the following code:

from core.models import Blog

def news(): 
    b = Blog(name='New Blog', tagline='All the latest news.')
    b.save()

My main app folder in django is called core and I have put my python file in there. In the shell I am able to do the import: from core import my_functions However I get an error AttributeError: module 'core.my_functions' has no attribute 'news' when I try to run the code my_functions.news(). How can I run the news function in the shell?

My tree structure is as follows:

core
    -__init__.py
    -admin.py
    -apps.py
    -models.py
    -my_functions.py
    -tests.py
    -urls.py
    -views.py

Everthing else works as normal but I just cant seem to figure why I cant do this simple import and run the function. I'm using VSCode.

Answer
1

Make sure there's an __init__.py file in the core directory. Then:

from core.my_functions import news

Also you have to restart your shell if you make changes to any file in your project, since the django shell will load all modules in memory at launch time.

How to use functions from a custom module in Python Django shell
See more ...