简体   繁体   中英

Running a python file other than views.py in django

I am running a django project and I want to divide up my python code into separate files. At the moment I am running my functions from views.py . In my views.py I have a plot function. I have taken this plotting code and I have created python file called plotting.py which has this plot function in it. this plotting file lives in the same folder as my views.py

My problem is accessing this plotting.py file. I am trying to access it through from the urls.py by path('plot', plotting.plot), . it is not working. Or do I have to link back to a function in views.py and from tat function go to plotting.py`?

urls.py should only import views and specify which URL should each view handle. Example:https://docs.djangoproject.com/en/3.0/topics/http/urls/#example

Since plot is a function (that probably is plotting something), this needs to go to the view, since it's the view that performs endpoint logic. So you need to import plot in the views file.

PS: path('plot', plotting.plot) would only work if plotting.plot was a view, but you mentioned it's just a function.

Is this plot function a view where you are returning a response to the client or is this a helper function that you are trying to call from within a view? If it isn't a view, I would recommend adding from.plotting import plot to the top of your views.py file

should you not do from plotting.py import plot and then you can use plot in views.py?

If your python version is less then 3.3, you need to create an empty file named __init__.py into the same directory as plotting.py to make your function importable.

And your plot function must be in function-based view format as demonstrated in django docs: https://docs.djangoproject.com/en/3.0/topics/http/views/#a-simple-view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM