{"id":813,"date":"2021-01-14T11:27:37","date_gmt":"2021-01-14T08:27:37","guid":{"rendered":"https:\/\/www.etemkeskin.com\/?p=813"},"modified":"2021-01-14T12:15:08","modified_gmt":"2021-01-14T09:15:08","slug":"how-to-make-dynamic-dropdown-list-with-ajax-in-python-django","status":"publish","type":"post","link":"https:\/\/www.etemkeskin.com\/index.php\/2021\/01\/14\/how-to-make-dynamic-dropdown-list-with-ajax-in-python-django\/","title":{"rendered":"How to Make Dynamic Dropdown List with Ajax in Python Django?"},"content":{"rendered":"\n<p>In Django projects, we may have data like categories and subcategories. We can present this data in forms with drop-down lists in the user interface. In this post, I will explain how to dynamically get subcategories from server  with ajax request without refreshing the page, depending on the selected category.<\/p>\n\n\n\n<p>There is a database structure with a parent category named <strong>subject<\/strong> where we will keep the software languages, and a database structure with subcategories named <strong>topic<\/strong> to hold the contents of the languages \u200b\u200brelated to this category.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"855\" height=\"302\" src=\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/01\/image-2.png\" alt=\"\" class=\"wp-image-820\"\/><\/figure>\n\n\n\n<p><br>As you can see in our HTML template below, while rendering the page, we render it with our <strong>subjects<\/strong> data. We will update our <strong>Topic<\/strong> drop-down list with the ajax request according to the <strong>subject<\/strong> selected from the drop-down list. <\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;htmlmixed&quot;,&quot;mime&quot;:&quot;text\/html&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;HTML&quot;,&quot;modeName&quot;:&quot;html&quot;}\">{% csrf_token %}\n&lt;div class=&quot;col-md-6&quot;&gt;\n  &lt;div class=&quot;form-group&quot;&gt;\n    &lt;label for=&quot;inputStatus&quot;&gt;Subject&lt;\/label&gt;\n    &lt;select id=&quot;question-subject&quot; class=&quot;form-control-sm custom-select&quot;&gt;\n      &lt;option selected disabled&gt;Choose a subject&lt;\/option&gt;\n      {% for subject in subjects%}\n      &lt;option value=&quot;{{subject.id}}&quot;&gt;{{subject.title}}&lt;\/option&gt;\n      {% endfor %}\n    &lt;\/select&gt;\n  &lt;\/div&gt;\n&lt;\/div&gt;\n&lt;div class=&quot;col-md-6&quot;&gt;\n  &lt;div class=&quot;form-group&quot;&gt;\n    &lt;label for=&quot;inputStatus&quot;&gt;Topic&lt;\/label&gt;\n    &lt;select id=&quot;question-topic&quot; class=&quot;form-control-sm custom-select&quot; name=&quot;topic&quot;&gt;\n      &lt;option selected disabled&gt;Choose a topic&lt;\/option&gt;\n    &lt;\/select&gt;\n  &lt;\/div&gt;\n&lt;\/div&gt;<\/pre><\/div>\n\n\n\n<p>To make an Ajax request, we first need to include the <strong>jquery<\/strong> library to our page.<\/p>\n\n\n\n<p>We define <code>id = \"question-subject\"<\/code> to our subject dropdown list. We select this list with the jquery selector and detect a change in this list with the <strong>change event<\/strong>. We assign the <strong>ID<\/strong> of the selected subject to a variable. Then, we make an ajax request to the address named <strong>get_topics_ajax<\/strong> and renew our topic list with the data returned from the request.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">{% block javascript %}\n&lt;script src=&quot;https:\/\/code.jquery.com\/jquery-3.5.1.js&quot; integrity=&quot;sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH\/C8ycbRAkjPDc=&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;\/script&gt;\n&lt;script&gt;\n    $(&quot;#question-subject&quot;).change(function () {\n        const subjectId = $(this).val();  \/\/ get the selected subject ID from the HTML dropdown list \n        $.ajax({                       \/\/ initialize an AJAX request\n            type: &quot;POST&quot;,\n            url: '{% url &quot;get_topics_ajax&quot; %}',\n            data: {\n                'subject_id': subjectId,       \/\/ add the country id to the POST parameters\n                'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(),\n            },\n            success: function (data) {   \/\/ `data` is from `get_topics_ajax` view function\n                let html_data = '&lt;option value=&quot;&quot;&gt;---------&lt;\/option&gt;';\n                data.forEach(function (data) {\n                    html_data += `&lt;option value=&quot;${data.id}&quot;&gt;${data.title}&lt;\/option&gt;`\n                });\n                $(&quot;#question-topic&quot;).html(html_data); \/\/ replace the contents of the topic input with the data that came from the server\n            }\n        });\n    });\n&lt;\/script&gt;\n{% endblock javascript %}<\/pre><\/div>\n\n\n\n<p>We define the <strong>url<\/strong> where the ajax request will be made in <code>urls.py<\/code> in the backend.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\"> path('get-topics-ajax\/', get_topics_ajax, name=&quot;get_topics_ajax&quot;),<\/pre><\/div>\n\n\n\n<p>We define our function that will work according to the url request in <code>view.py<\/code> as follows. <\/p>\n\n\n\n<p>According to the <strong>subject_id<\/strong>, we get the <strong>topics<\/strong> related to it from the database. We send <strong>topics<\/strong> as <strong>json<\/strong> data to frontend. If there is a problem, we send an <strong>error<\/strong> message to frontend.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">from quiz.models import Question, Topic, Subject\nfrom django.http import JsonResponse,\n\ndef get_topics_ajax(request):\n    if request.method == &quot;POST&quot;:\n        subject_id = request.POST['subject_id']\n        try:\n            subject = Subject.objects.filter(id = subject_id).first()\n            topics = Topic.objects.filter(subject = subject)\n        except Exception:\n            data['error_message'] = 'error'\n            return JsonResponse(data)\n        return JsonResponse(list(topics.values('id', 'title')), safe = False) <\/pre><\/div>\n\n\n\n<p>Good luck.<\/p>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container\">\n<p><\/p>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>In Django projects, we may have data like categories and subcategories. We can present this data in forms with drop-down lists in the user interface. In this post, I will explain how to dynamically get subcategories from server with ajax request without refreshing the page, depending on the selected category. There is a database structure [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[30,4],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v16.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Make Dynamic Dropdown List with Ajax in Python Django? - blog website<\/title>\n<meta name=\"description\" content=\"In Django projects, we may have data with categories and subcategories. We can present this in forms with drop-down lists in the user interface. In this post, I will explain how to dynamically pull from server subcategories with ajax without refreshing the page, depending on the selected category. There is a database structure with a parent category named subject where we will keep the software languages, and a database structure with subcategories named topic to hold the contents of the languages \u200b\u200brelated to this category.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.etemkeskin.com\/index.php\/2021\/01\/14\/how-to-make-dynamic-dropdown-list-with-ajax-in-python-django\/\" \/>\n<meta property=\"og:locale\" content=\"tr_TR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Make Dynamic Dropdown List with Ajax in Python Django? - blog website\" \/>\n<meta property=\"og:description\" content=\"In Django projects, we may have data with categories and subcategories. We can present this in forms with drop-down lists in the user interface. In this post, I will explain how to dynamically pull from server subcategories with ajax without refreshing the page, depending on the selected category. There is a database structure with a parent category named subject where we will keep the software languages, and a database structure with subcategories named topic to hold the contents of the languages \u200b\u200brelated to this category.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.etemkeskin.com\/index.php\/2021\/01\/14\/how-to-make-dynamic-dropdown-list-with-ajax-in-python-django\/\" \/>\n<meta property=\"og:site_name\" content=\"blog website\" \/>\n<meta property=\"article:published_time\" content=\"2021-01-14T08:27:37+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-01-14T09:15:08+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/01\/image-2.png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Tahmini okuma s\u00fcresi\" \/>\n\t<meta name=\"twitter:data1\" content=\"3 dakika\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.etemkeskin.com\/#website\",\"url\":\"https:\/\/www.etemkeskin.com\/\",\"name\":\"blog website\",\"description\":\"Etem KESK\\u0130N\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/www.etemkeskin.com\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"tr\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/01\/14\/how-to-make-dynamic-dropdown-list-with-ajax-in-python-django\/#primaryimage\",\"inLanguage\":\"tr\",\"url\":\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/01\/image-2.png\",\"contentUrl\":\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/01\/image-2.png\",\"width\":855,\"height\":302},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/01\/14\/how-to-make-dynamic-dropdown-list-with-ajax-in-python-django\/#webpage\",\"url\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/01\/14\/how-to-make-dynamic-dropdown-list-with-ajax-in-python-django\/\",\"name\":\"How to Make Dynamic Dropdown List with Ajax in Python Django? - blog website\",\"isPartOf\":{\"@id\":\"https:\/\/www.etemkeskin.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/01\/14\/how-to-make-dynamic-dropdown-list-with-ajax-in-python-django\/#primaryimage\"},\"datePublished\":\"2021-01-14T08:27:37+00:00\",\"dateModified\":\"2021-01-14T09:15:08+00:00\",\"author\":{\"@id\":\"https:\/\/www.etemkeskin.com\/#\/schema\/person\/dcbc30282861ce578b96a79ce8789629\"},\"description\":\"In Django projects, we may have data with categories and subcategories. We can present this in forms with drop-down lists in the user interface. In this post, I will explain how to dynamically pull from server subcategories with ajax without refreshing the page, depending on the selected category. There is a database structure with a parent category named subject where we will keep the software languages, and a database structure with subcategories named topic to hold the contents of the languages \\u200b\\u200brelated to this category.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/01\/14\/how-to-make-dynamic-dropdown-list-with-ajax-in-python-django\/#breadcrumb\"},\"inLanguage\":\"tr\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.etemkeskin.com\/index.php\/2021\/01\/14\/how-to-make-dynamic-dropdown-list-with-ajax-in-python-django\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/01\/14\/how-to-make-dynamic-dropdown-list-with-ajax-in-python-django\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Ana sayfa\",\"item\":\"https:\/\/www.etemkeskin.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Make Dynamic Dropdown List with Ajax in Python Django?\"}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.etemkeskin.com\/#\/schema\/person\/dcbc30282861ce578b96a79ce8789629\",\"name\":\"etemkeskin\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/www.etemkeskin.com\/#personlogo\",\"inLanguage\":\"tr\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/6af0148b790691ed24ae245fb3dc773b?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/6af0148b790691ed24ae245fb3dc773b?s=96&d=mm&r=g\",\"caption\":\"etemkeskin\"},\"url\":\"https:\/\/www.etemkeskin.com\/index.php\/author\/etemkeskinyahoo-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","_links":{"self":[{"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/posts\/813"}],"collection":[{"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/comments?post=813"}],"version-history":[{"count":81,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/posts\/813\/revisions"}],"predecessor-version":[{"id":903,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/posts\/813\/revisions\/903"}],"wp:attachment":[{"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/media?parent=813"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/categories?post=813"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/tags?post=813"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}