Good afternoon, I'm new to Django, and I'm trying to create a web design with Material Design, using django-material, a package for Django forms that apply this style, and I have the following problem:
What I want to do is how well it puts in the title of my question is, enable and disable a ModelChoiceField that depends on another.
I have a ModelChoiceField called "Categories" and another "Subcategories". When loading the page has to be disabled, and my intention is that while a category is not selected, the control of subcategories is disabled, and when a category has been selected, it is enabled. For this I have been using JQuery.
This in Django without the style of this package, I have no problem, but when you add this package, to apply this style (which creates in HTML div, ul, input, nested select) complicates it in a way that I can not do the disabling and enabling of controls.
In the code there are two commented selectors that I have tried by logic, but they do not work at the moment of loading the page.
Here is a capture of the HTML that forms the django-material package:
Here is the code of my forms.py
class RegistroProductoForm(forms.Form):
categorias = forms.ModelChoiceField(queryset=Categoria.objects, empty_label='Seleccione una categoría...',)
subcategorias = forms.ModelChoiceField(queryset=Subcategoria.objects, empty_label='Seleccione una subcategoría...')
Here the code of my template
{% load staticfiles %}
{% include 'material/includes/material_css.html' %}
<script src="{% static 'material/js/jquery-2.2.0.js' %}"></script>
{% include 'material/includes/material_js.html' %}
{% load material_form %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="POST" action="">{% csrf_token %}
{% form form=form %}{% endform %}
<button type="submit" name="_submit" class="waves-effect waves-light btn btn-primary btn-lg">Enviar</button>
</form>
<script charset="utf-8" type="text/javascript">
$(document).ready(function () {
// Con este selector se bloquea al cargar la página, pero luego se queda bloqueado el control aunque se vea habilitado de nuevo
$('#id_subcategorias').attr('disabled', true);
//Con este selector, que es el mismo que está dentro del if, directamente no deshabilita al cargar la página
$("#id_subcategorias_container").find('input').attr('disabled',true);
$('#id_categorias').on('change', function () {
var id_categoria = $('#id_categorias').val();
var id_subcategoria = $('#id_subcategorias').val();
if(id_categoria == ''){
$("#id_subcategorias_container").find('input').attr('disabled',true);
}else{
$("#id_subcategorias_container").find('input').removeAttr('disabled');
}
});
I do not know what else to do anymore, I hope I have explained myself well and that you can see the solution that I do not see for this problem.
Thank you.