Я пытаюсь создать раскрывающееся меню Dynami c и получаю эту ошибку в консоли.
Uncaught TypeError: $.ajax is not a function
at HTMLSelectElement.<anonymous> ((index):148)
at HTMLSelectElement.dispatch (jquery-3.4.1.min.js:2)
at HTMLSelectElement.v.handle (jquery-3.4.1.min.js:2)
Я слежу за страницей, чтобы сделать это раскрывающееся меню, и это ссылка .
views.py
from django.shortcuts import render
from . import forms
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_protect
from django.forms import modelformset_factory
import requests
import urllib.parse
from apply_main.models import *
def apply(request):
def getLonLat(subdistrict,district,state):
address = str(subdistrict)+", "+str(district)+", "+str(state)
url = 'https://nominatim.openstreetmap.org/search/' + urllib.parse.quote(address) +'?format=json'
response = requests.get(url).json()
return response[0]["lat"],response[0]["lon"]
form = forms.ApplyForm()
if request.method == 'POST':
form = forms.ApplyForm(request.POST)
if form.is_valid():
application = form.save(commit=False)
application.save()
return HttpResponseRedirect(reverse('apply_main:apply'))
context = {
'form':form,
}
return render(request, 'apply_main/apply_form.html', context)
def load_districts(request):
state_id = request.GET.get('state')
print(state_id,"\n"*5)
districts = District.objects.filter(state_id=state_id).order_by('name')
return render(request, 'apply_main/dist_dropdown_list_options.html', {'districts': districts})
def load_subdistricts(request):
district_id = request.GET.get('district')
subdistricts = Subdistrict.objects.filter(district_id=district_id).order_by('name')
return render(request, 'apply_main/subdist_dropdown_list_options.html', {'subdistricts': subdistricts})
model.py
from django.db import models
from django.contrib.auth.models import User
class State(models.Model):
name = models.CharField(max_length=64)
def __str__(self):
return self.name
class District(models.Model):
name = models.CharField(max_length=64)
state = models.ForeignKey(State,on_delete=models.CASCADE)
def __str__(self):
return self.name
class Subdistrict(models.Model):
name = models.CharField(max_length=64)
district = models.ForeignKey(District,on_delete=models.CASCADE)
def __str__(self):
return self.name
class Apply(models.Model):
first_name = models.CharField(max_length=64)
middle_name = models.CharField(max_length=64,blank=True)
last_name = models.CharField(max_length=64)
aadhaar_number = models.IntegerField(unique=True,blank=False)
published = models.DateTimeField(auto_now_add=True)
phone_number = models.IntegerField(unique=True,blank=False)
dob = models.DateField()
lon = models.FloatField()
lat = models.FloatField()
subdistrict = models.ForeignKey(Subdistrict,on_delete=models.CASCADE)
district = models.ForeignKey(District,on_delete=models.CASCADE)
state = models.ForeignKey(State,on_delete=models.CASCADE)
def __str__(self):
return str(self.first_name)
forms.py
from django import forms
from apply_main.models import *
class ApplyForm(forms.ModelForm):
dob = forms.DateField(widget=forms.DateInput(
attrs={
'placeholder': 'MM/DD/YYYY'
}
))
middle_name = forms.CharField(widget=forms.TextInput(
attrs={
'placeholder':'Optional'
}
))
class Meta:
model = Apply
fields = [
'first_name',
'middle_name',
'last_name',
'aadhaar_number',
'phone_number',
'dob',
'state',
'district',
'subdistrict',
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['district'].queryset = District.objects.none()
self.fields['subdistrict'].queryset = Subdistrict.objects.none()
URL .py
from django.urls import path
from . import views
from donate import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
app_name = "apply_main"
urlpatterns = [
path('apply/',views.apply,name='apply'),
path('ajax/load-districts/', views.load_districts, name='ajax_load_districts'),
path('ajax/load-subdistricts/', views.load_subdistricts, name='ajax_load_subdistricts'),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
apply_form. html
{% extends 'base.html' %}
{% load static %}
{% block head_block %}
<link rel="stylesheet" type="text/css" href="{% static 'index.css' %}">
{% endblock head_block %}
{% block body_block %}
<h2>Person Form</h2>
<form method="post" id="applyForm" data-districts-url="{% url 'apply_main:ajax_load_districts' %}" data-subdistricts-url="{% url 'apply_main:ajax_load_subdistricts' %}" novalidate>
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<button type="submit">Save</button>
</form>
<script>console.log("outside");</script>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script>
$("#id_state").change(function () {
var url = $("#applyForm").attr("data-districts-url"); // get the url of the `load_cities` view
var stateId = $(this).val(); // get the selected country ID from the HTML input
console.log("inside");
console.log(url);
console.log(stateId);
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
data: {
'state': stateId // add the country id to the GET parameters
},
success: function (data) { // `data` is the return of the `load_cities` view function
$("#id_district").html(data); // replace the contents of the city input with the data that came from the server
}
});
});
$("#id_district").change(function () {
var url = $("#applyForm").attr("data-subdistricts-url"); // get the url of the `load_cities` view
var districtId = $(this).val(); // get the selected country ID from the HTML input
console.log("inside");
console.log(url);
console.log(districtId);
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
data: {
'district': districtId // add the country id to the GET parameters
},
success: function (data) { // `data` is the return of the `load_cities` view function
$("#id_subdistrict").html(data); // replace the contents of the city input with the data that came from the server
}
});
});
</script>
{% endblock %}
dist_dropdown_list_options. html
<option value="">---------</option>
{% for district in districts %}
<option value="{{ district.id }}">{{ district.district_name }}</option>
{% endfor %}
subdist_dropdown_list_options. html
<option value="">---------</option>
{% for subdistrict in subdistricts %}
<option value="{{ subdistrict.id }}">{{ subdistrict.subdistrict_name }}</option>
{% endfor %}
Сообщите мне, если потребуется дополнительная информация.
Ссылка на GitHub - https://github.com/deshiyan1010/electronics-donation