简体   繁体   中英

How import a function from another view with Django?

I have this folder hierarchy:

|---- saga
    |---- core
         |---- views.py
    |---- study_time
         |---- views.py

On my study_time/views.py , I have this functions:

def study_time(request):
    def tasks_subjects(week_day, key):
        #Code here
        return __tasks

    def day_studies(week_day):
        __tasks_subjects = tasks_subjects(week_day, 0)
        #Code here
        return __studies

    return render(request, 'study_time.html', context)

On my core/views.py , I need the day_studies() function, so I'm importing like this:

from saga.study_time.views import day_studies
    def home(request):
        day_progress = day_studies(datetime.date.today().isoweekday())

But I'm getting the error:

ImportError: cannot import name 'day_studies'

How can I make this importation? I don't want to reply all code.

You've defined a nested function. That simply isn't visible outside the containing function; in fact, making it invisible from outside is pretty much the only good reason for defining nested functions in Python. Don't do that; move it outside the study_time function.

(Also, don't use double-underscore prefixes like that. They don't make any sense outside a class; and even there you should rarely if ever use them.)

The inner function is not accessible,because it is local code for that function only. It is not generic for all in the views.py . So make a distinction on this.

Go through this for better understanding!! https://realpython.com/blog/python/inner-functions-what-are-they-good-for/

Happy coding!!

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