0

The program open Bootstrap Modal and load Django Form to create new permission, this is works. But when i want in the form add new Ajax call to load dynamically elements in Django ChoiceField appears the error and browser not finish the call never.

I open browser inspect console and appears XMLHttpRequest error

url.py:

path('permisos/', general_views.permission_list,name='permission_list'),
path('permisos/crear', general_views.permission_create, name='permission_create'),
path('permisos/<int:id>/editar', general_views.permission_update, name='permission_update'),
path('permisos/<int:id>/detalle', general_views.permission_detail, name='permission_detail'),
path('permisos/<int:id>/borrar', general_views.permission_delete, name='permission_delete'),

path('permisos/crear/cargar_elementos/', general_views.permission_load, name='ajax_load_permissions'),

never get to call this function from ajax

views.py:

def permission_load(request):
  type = request.GET.get('type')

  if type == 2: # object
    list = ['general', 'billing', 'accounting']
    elements = ContentType.objects.filter(app_label__in=list)

  elif type == 3: # instance
    list = ['general', 'billing', 'accounting']
    content_type = ContentType.objects.filter(app_label__in=list)
    elements = general_models.content_type.model.objects.all()

  elif type == 4: # attribute
    list = ['general', 'billing', 'accounting']
    content_type = ContentType.objects.filter(app_label__in=list)
    elements = general_models.content_type.model.objects.all()
    # get instance atributtes

  else: # module
    elements = general_models.Modules.objects.all()

  # other aspect is that i dont know how to load view result in the html choicefield

  response = { 'element': elements }
  json = simplejson.dumps(response)
  return HttpResponse(json, mimetype="text/json")

forms.py:

class CustomPermisisonForm(forms.Form):
  name = forms.CharField()

  ACTION_TYPE = ((1, ('Ver')),(2, ('Añadir')),(3, ('Modificar')),(4, ('Borrar')))
  action = forms.MultipleChoiceField(choices=ACTION_TYPE, label='Acciones', initial=1, widget=forms.SelectMultiple())

  PERMISSION_TYPE = ((1, ('Módulo')),(2, ('Objecto')),(3, ('Instancia')),(4, ('Atributo')))
  type = forms.ChoiceField(choices=PERMISSION_TYPE, label='Tipo', initial=1, widget=forms.Select(attrs={"data-objects-url":"{% url 'ajax_load_permissions' %}"}))

  element = forms.ModelChoiceField(queryset=general_models.Module.objects.all())

permissions.html:

{% block javascript %}
  <script src="{% static 'js/permissions.js' %}"></script>
{% endblock %}

# this is the line to open modal
<button type="button" onclick="return openModalPermission('{% url 'general:permission_create' %}')" class="btn btn-outline-primary float-right btn-sm">
  <span class="fas fa-plus"></span>
</button>

permission_create.html:

{% load static %}

<div class="modal-dialog modal-lg">
  <div class="modal-content">
    <form method="POST" action="{% url 'general:permission_create' %}">
      {% csrf_token %}
      <div class="modal-header">
        <h4 class="modal-title">Nuevo Permiso</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        {% include 'permission_form.html' %}
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-primary">Crear</button>
      </div>
    </form>
  </div>
</div>

# when comment this line the error disappear but don't work js call
<script src="{% static 'js/permissions.js' %}"></script>

permission_form.html:

{% load widget_tweaks %}
{% load static %}

{% for field in form %}
  <div class="form-group{% if field.errors %} has-error{% endif %}">
    <label for="{{ field.id_for_label }}">{{ field.label }}</label>
    {% render_field field class="form-control" %}
    {% for error in field.errors %}
      <p class="help-block">{{ error }}</p>
    {% endfor %}
  </div>
{% endfor %}

permissions.js:

function openModalPermission(url) {
  $('#modal-permission').load(url, function() {
    $(this).modal('show');
  });
  return false;
}

$("#id_type").change(function () {
  console.log("js function");
  var url = $("id_type").attr("data-objects-url");
  var type = $(this).val();
  console.log(type);
  console.log(url);
  $.ajax({
    url: url,
    data: {
      'type': type
    },
    success: function (data) {
      $("#id_element").html(data);
    },
    error: function (qXHR, textStatus, errorThrown) {
      console.log(qXHR)
      console.log(textStatus)
      console.log(errorThrown)
    }
  });
  return false;
});

Anybody know how to solve this problem ? Thanks in advance.

  • Please post the exact error message from the console. What does _"but don't work js call"_ mean exactly? Do you see `"js function"` in the console? If not then I would guess that there's no element with id `id_type` in the DOM when you want to add the `change` handler. – Andreas Nov 26 '18 at 12:01
  • This is the exact error: Un XMLHttpRequest síncrono en el hilo principal está desaprobado por sus efectos negativos en la experiencia del usuario final. Para más ayuda vea http://xhr.spec.whatwg.org/ and appear in browser inspect console when in click on add button in permission.html – Alberto Sanmartin Martinez Nov 26 '18 at 12:06
  • _"A synchronous XMLHttpRequest in the main thread is deprecated for its negative effects on the end user experience."_ - That's not an error but a deprecation _warning_. – Andreas Nov 26 '18 at 12:07
  • "js function" message doesn't appear – Alberto Sanmartin Martinez Nov 26 '18 at 12:16
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Andreas Nov 26 '18 at 12:18
  • Thank you so much !! Solve in edited. – Alberto Sanmartin Martinez Nov 26 '18 at 12:37
  • 1
    Editing the question so it doesn't show the problem anymore isn't helpful for future readers. Either rollback your changes and add the solution as an answer, rollback the changes and accept the duplicate or delete the question. But you should really rollback the changes made. – Andreas Nov 26 '18 at 12:43

1 Answers1

0

SOLVED

permissions.html:

<!-- pass this block to the end of the file -->
{% block javascript %}
  <script src="{% static 'js/permissions.js' %}"></script>
{% endblock %}