Home > other >  Best way to incorporate a "utils" module in a django project?
Best way to incorporate a "utils" module in a django project?

Time:08-15

I'm creating a project that will have several app named after states, such as:

|-my_state_project
|---my_state_project
|---new_jersey
|---alabama
|---rhode_island

I want to create a utils module that each app can import from. The utils.py file inside the utils module will have functions used to scrape data from the web using bs4. Each app will have a jobs.py script to import from utils.py. So the project will look like:

|-my_state_project
|---my_state_project
|---new_jersey
|------jobs.py
|---alabama
|------jobs.py
|---rhode_island
|---utils
|------utils.py

My questions are:

  1. Is this how Django projects are usually structured?
  2. I'm getting a ModuleNotFoundError: No module named 'utils.py' while trying to import inside one of the jobs.py files. I'm importing it using from utils import utils. Why is it complaining? This should be rudimentary

The alternative would be to create a utils.py file inside each app which doesn't seem very pythonic (especially since the utils.py file may grow and updating each file individually would be torture :)

CodePudding user response:

For 1st question, I have no solid answer, but I did similar things: put a utils.py inside an app.

The structure:

|- my_project
|--- my_project
|--- home
|----- models.py
|----- forms.py
|----- views.py
|----- utils.py
|----- urls.py
|----- templatetags
|--- rest_of_my_project

My home app serves only 3 purpose:

  1. custom User model,
  2. custom admin site, and
  3. functions, custom Views, custom FormSets, etc within utils.py, and also custom template tags.

I don't think there is anything wrong with your structure.

For 2nd question, did you forget to include 'utils' in INSTALLED_APPS in settings.py?

CodePudding user response:

For the first question - I do something similar, creating an app called 'universal' that contains all the elements that multiple apps use: my base.html template, my sitewide static CSS etc. I also have a utils.py in there!

For the second question: To reference it, the simple solution is...

from utils.utils import function_name, function_name2

so from appname.filename import function_name

  • Related