How to add onchange event in django-python
Written by Parvatiandsons Team
Codes with on change in category to subcategory..
Forms.py
from django import forms
from .models import BlogSubCategory
class BlogForm(forms.ModelForm):
class Meta:
model = BlogSubCategory
fields = "__all__"
widgets = {'category':forms.Select(attrs={'onchange':'fn_GetSubcategory()'})}
views.py
from django.shortcuts import render,HttpResponse
from django.core import serializers
from .models import Blog,BlogSubCategory,BlogCategory
# Create your views here.
def getsubcategorybycategory(request, pk):
try:
__Data = BlogSubCategory.objects.filter(category__id=pk)
qu_json = serializers.serialize('json', __Data)
return HttpResponse(qu_json, content_type='application/json')
except Exception as er:
return HttpResponse(er, content_type='application/json')
Name.js
function fn_TestJSON(text) {
if (typeof text == "string") {
return false;
}
try {
text = JSON.stringify(text)
JSON.parse(text);
return true;
} catch (error) {
console.log(error)
return false;
}
}
function fn_GetSubcategory() {
__ID = $('#id_category').val()
$.ajax({
url: '/subcategory/' + __ID + '/',
}).done(function(res) {
if (fn_TestJSON(res)) {
var objHTML = '<option value="0">select subcategory </opction>'
if (fn_TestJSON(res)) {
$.each(res, function() {
objHTML += '<option value="' + this.pk+ '">' + this.fields.name + '</option>'
})
}
$('#id_subcategory').empty().append(objHTML)
}
});
}
Urls.py
from blogs.views import getsubcategorybycategory
urlpatterns = [
path('admin/', admin.site.urls),
path('subcategory/<int:pk>/', getsubcategorybycategory, name='getsubcategorybycategory'),
]
Admin.py
from .forms import BlogForm
class BlogAdmin(admin.ModelAdmin):
form = BlogForm
class Media:
js = (
"js/jquery.js",
"js/blog.js",
)