django - reusing functions in many views

风格不统一 提交于 2019-12-06 08:17:10

Django views are just Python functions. You can call other Python functions from them just as you can from any other Python code. Put your functions into a .py file, import it, and invoke the functions.

Of course, it may make sense for other reasons to create a class to hold the functions, but you certainly don't need to in order to call them from views.

The solution would be to create the myfunctions.py file in your app folder and import it in your views. Your views file would look like:

import myfunctions

def my_view(request):
    .....
    foo = myfunctions.bar()
    ....

From my point of view, if you have a lot of functions that are widely used in your project it make sense put all this in some separate application. I create some module named 'contrib' for this purposes. It can avoid some time for maintaining this code in future

You look to complicated to Django. Django is just another Python application and lives in the Python world. For example you can create file library.py and import this file where is needed (in modules where the function from library is needed). If you need you library's functions to get data from database, just import models in the library.py and use them.

Django doesn't have such a big think as "module". You creating the architecture, you can define what in your case is module. In general this is just simple directory with init.py file inside to be able to import files from there.

Hope that helped.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!