How do I set up a view/path to an AJAX call in Django?

时间:2019-04-16 22:39:18

标签: ajax django python-3.x django-views django-urls

I'm using Django and Python 3.7. I have this file in my project

web/views/tax_calculator.py

which consists of a single function (I'm leaving out the imports) ...

def calculate_taxes(request):
    state = request.GET.get('state', None)
    gross_income = request.GET.get('gross', None)
    owner_salary = request.GET.get('salary', None)

    data = {
        'sole_pr_taxes': TaxCalculatorService.calc_sole_pr_taxes(state, gross_income),
        's_corp_taxes': TaxCalculatorService.calc_s_corp_taxes(state, gross_income, owner_salary),
    }
    return JsonResponse(data)

In my ./myproject/urls.py file I have

from django.contrib import admin
from django.urls import path
from web.views import *

urlpatterns = [
    path(r'^ajax/calculate_taxes/$', tax_calculator.calculate_taxes, name='calculate_taxes'),
]

but this results in an error

    path(r'^ajax/calculate_taxes/$', tax_calculator.calculate_taxes, name='calculate_taxes'),
NameError: name 'tax_calculator' is not defined

What's the right way to reference my view/AJAX call?

3 个答案:

答案 0 :(得分:0)

Usually calculate_taxes would be defined in web/views.py, then it can simply be referred to as calculate_taxes.

答案 1 :(得分:0)

Inside your web/views directory in the __init__.py file you have to import tax_calculator.py like this:

# __init__.py
from . import tax_calculator

If you don’t have the __init__.py file you have to create it.

答案 2 :(得分:0)

尝试将您的urls.py代码更改为以下代码

from django.contrib import admin
from django.urls import path
from web.views.tax_calculator import calculate_taxes

urlpatterns = [
    path(r'^ajax/calculate_taxes/$', calculate_taxes, name='calculate_taxes'),
]
相关问题