Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a class from a python file in django?

I'm currently using django and putting python code in my views.py to run them on my webpages. There is an excerpt of code that requires a certain class from a python file to work sort of like a package but it is just a python file I was given to use in order to execute a certain piece of code. How would I be able to reference the class from my python file in the django views.py file? I have tried putting the python file in my site packages folder in my Anaconda3 folder and have tried just using from [name of python file] import [class name] in the views.py file but it does not seem to recognize that the file exists in the site packages folder. I also tried putting the python file in the django personal folder and using from personal import [name of file] but that doesn't work either

like image 967
user3354383 Avatar asked Dec 06 '22 17:12

user3354383


1 Answers

Every views.py file belongs to an app in django created as:

django-admin startapp my_app

so your views.py file is in my_app folder. If your custom python file is in the same folder you can simply do:

     from my_app.custom_file import ClassName  # Don't forget to update app name

or

from .custom_file import ClassName  # Don't forget to update app name

If your python file is in another app folder then update the app name respectively.

like image 86
Justin M. Ucar Avatar answered Dec 27 '22 09:12

Justin M. Ucar