Django Crispy Forms do not support JavaScript functionality

In my project, I am working on creating a client form where the country, province, and city are selected based on different models:

class Country(models.Model):
      Country = models.CharField(max_length=100, unique=True)
      def __str__(self):
          return self.Country

  class Province(models.Model):
      province = models.CharField(max_length=100, unique=True)
      Country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='province', null=True)
      def __str__(self):
          return self.province

  class City(models.Model):
      city = models.CharField(max_length=100, unique=True)
      Province = models.ForeignKey(Province, on_delete=models.CASCADE, related_name='city', null=True)
      def __str__(self):
          return self.city
  

The goal is to dynamically update the list of provinces when a country is selected, and similarly for cities. To achieve this, I have created URLs and written the following code in my views.py:

class GetProvincesView(View):
      def get(self, request, *args, **kwargs):
          country_id = request.GET.get('country_id')
          provinces = Province.objects.filter(Country_id=country_id)
          data = [{'id': province.id, 'name': province.province} for province in provinces]
          return JsonResponse(data, safe=False)


  class GetCitiesView(View):
      def get(self, request, *args, **kwargs):
          province_id = request.GET.get('province_id')
          cities = City.objects.filter(Province_id=province_id)
          data = [{'id': city.id, 'name': city.city} for city in cities]
          return JsonResponse(data, safe=False)
  

Below is a snippet of the template, model, and form that I am using for the client creation:

(template, models, and form snippets go here)

However, an issue I am facing is that when selecting a country, the province field does not update as expected. I have checked the console and added console logs in my code, but no logs appear in Chrome developer tools.

I am using Cookiecutter. Could it be possible that the base.html standard layout is affecting the functioning of my scripts on the page?

Answer №1

Upon further investigation, I believe I have identified the issue. The Base.html file already has defined blocks for javascript:

 {% block inline_javascript %}
    {% comment %}
    Script tags with only code, no src (defer by default). To run
    with a "defer" so that you run inline code:
    <script>
      window.addEventListener('DOMContentLoaded', () => {/* Run whatever you want */});
    </script>
    {% endcomment %}
    {% endblock inline_javascript %}

I am attempting to replace {% block scripts %} with {% block inline_javascript %} in my code. Currently, I am encountering an error indicating that my javascript is executing. Although there is another issue present, I will work towards resolving it :-) (it appears to be a code-related problem in my javascript)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to prevent the onClick event from triggering during the page rendering process?

I am currently working with React, Gatsby, and Material UI Buttons. I'm facing an issue where the most recently pressed button is getting disabled along with all other buttons when running my code. Despite already implementing bindings, as suggested b ...

What is the best way to run a lengthy task in Node.js by periodically checking the database for updates?

In my current setup, there is a routine that continuously checks the database for any pending work orders. Upon finding one, it needs to execute it promptly. The system can handle only one work order at a time, and these tasks may vary in duration from 5 s ...

What is the best way to verify if an Android permission request has been successfully granted or denied

I've been working on my RN application and encountered the following code snippet. import { PermissionsAndroid } from 'react-native'; export default new Promise(() => { return PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS ...

Creating an embedded link to a website that adjusts to different screen sizes while also dynamically changing

I've been developing a personalized site builder that includes an iframe for previewing responsive websites. In order to make the site 'zoomed out' and not appear in mobile size, I'm utilizing CSS scale and transform origin as shown bel ...

The value of req.body.name cannot be determined in Express using Node.js

I want to implement a like/dislike feature on my website using HTML and JavaScript. Here is the code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> <input type="submit" name="vote" value= ...

Error: The current component does not have a template or render function specified. Check the <App>

I am a beginner in Vue js and I am facing an issue while running my application. It is showing an empty page with the error message: Component is missing template or render function. at <App>. Additionally, there is also a warning from Vue Router sa ...

Having trouble with your mobile dropdown menu not responding to clicks?

I'm having trouble getting a dropdown menu to work on the mobile version of my website. When I click on the dropdown menu image, it's supposed to appear, but it's not working as expected. JSFiddle: https://jsfiddle.net/xfvjv184/ Included ...

Tips for incorporating a hashbang into a JavaScript file that is executable without compromising browser compatibility

Is it possible to run code like this in both Node.js and the browser? #! /usr/local/bin/node console.log("Hello world") I have a script that I currently run locally in Node.js, but now I want to also execute it in the browser without having to modify it ...

Working with Django: invoking both the base and customized save methods

Forgive me if this sounds like a beginner question, but it's been bothering me lately (I'm still learning the ropes of both Django and Python). Within my Django application, I have overridden the save() method in a model to execute some tasks re ...

Problems with Atom's ternjs autocomplete feature

My project structure is as follows: https://i.sstatic.net/J9Pk4.png The content of .tern-project is: { "ecmaVersion": 6, "libs": [ "browser", "jquery" ], "loadEagerly": [ "/bower-components/d3/d3.js" ] } I attempted to change d3.j ...

JQuery Slideshow Automation

I have created a slideshow using Javascript and JQuery for my webpage. However, I am encountering an issue where only one of the slideshows cycles through all the pictures and then starts over, while the second one ends after cycling once. Can someone as ...

Trigger an event upon completion of a write operation in AngularJS

I want to trigger a search after my user finishes typing (without hitting enter) in AngularJS. Here is a simplified version of my HTML: <div ng-class="input-append" ng-controller="searchControl"> <input type="text" ng-model="ajaxSearch" ng-cha ...

What is the best way to retrieve JavaScript Values through Selenium?

Currently, I am working with Java selenium client and running this code snippet. The variable PAGE_NUMBER is assigned a value; however, when using selenium, I'm unable to retrieve it: String script = "var cellValue = selenium.browserbot.getUserWindow ...

Setting a displacement/normal map for only one face of a cylinder

My current setup involves creating a cylinder using the following code: var geometry = new THREE.CylinderGeometry( 50, 50, 2, 128 ); The resulting shape is a flat cylinder resembling a coin. However, when I apply a displacementMap and normalMap, I notice ...

AngularJS does not recognize the service being referenced

I keep encountering an error in AngularJS saying that the service is not defined, even though my controller and module are properly connected: application.js: var myapp=angular.module('myApp', []); myapp.service('productService', fun ...

Methods for extracting the date value from a Material UI datepicker?

As a newcomer to React, I am currently working on creating a form that includes a Date picker for scheduling appointments. Since booking appointments in the past is not allowed, I need to disable the days before today in the calendar for the date picker. ...

Open the navigation menu by clicking on either the navigation links or anywhere outside of it

Seeking a solution for my mobile navigation menu that closes when clicking outside the links or on one of them, without using jQuery. How can I achieve this with JavaScript ES6? Current code snippet: const navSlide = () => { const burger = docum ...

Mirage blocking Ember.js ajax POST request from going through

Currently, I am in the process of writing tests for a component within my Ember application. This particular component is responsible for executing an ajax POST request to communicate with my servers API and retrieve a file location string as a response. ...

Issue with NodeJS Express's reverse proxy due to an invalid TLS certificate alternative name

I have configured a reverse proxy on my endpoint as shown below: var express = require('express'); var app = express(); var httpProxy = require('http-proxy'); var apiProxy = httpProxy.createProxyServer(); var serverOne = 'https://i ...

Changing color based on AngularJS condition using CSS

My HTML code looks like this: <div> <i class="glyphicon glyphicon-envelope" style="margin-top: -50px; cursor:pointer; color: #1F45FC" ng-click="createComment(set_id)"> </i> Route <center> ...