1

I need to create a form with 5 select fields, each one dependent of the previous one (Schools, Disciplines, Macro-Content, Micro-Content, Teacher)

I'm able to get only one working, passing an Ajax view to the form div:

  <form action="" id="orderForm" method="POST" discipline-queries-url="{% url 'ajax-load-discipline' %}>

and

<script src="//code.jquery.com/jquery-3.6.0.js"></script>
  <script>
    $("#institute").change(function () {
        const url = $("#orderForm").attr("discipline-queries-url");
        const instituteId = $(this).val();

        $.ajax({
            url: url,
            data: {
                'institute_id': instituteId
            },
            success: function (data) { 
                $("#discipline").html(data);
            }
        });

    });
</script>

From what I understand I'd need 4 different ajax views, one for each database query, and pass the url attribute through modelform attributes like this:

            'discipline': forms.Select(attrs={'id': 'discipline', 'class': 'form-control',
                                              'discipline-queries-url': '{% url "ajax-load-discipline" %}'}),

But the special characters are escaping and returning something like this:

"GET /order/create/%7B%%20url%20%22ajax-load-discipline%22%20%%7D?institute_id=1 HTTP/1.1" 404 13568

So it is passing {% url "ajax-load-discipline" %} to the url...

Any idea of what I can do to pass the correct parameters?

1
  • Ok, I made it work passing the full URL direct to the ajax javascript: url: 'localhost:8000/ajax/load-discipline-details', BUT OH BOY this looks wrong. Any idea how to make it work direct by django templatetags? Commented May 24, 2021 at 1:41

1 Answer 1

2

When you set attributes for a widget, it does not get rendered as if it were part of the template, it gets rendered as if it were a variable being rendered in the template, hence instead of "{% url 'ajax-load-discipline' %}" you should be writing the url itself there using reverse_lazy [Django docs]:

from django.urls import reverse_lazy


'discipline': forms.Select(attrs={'id': 'discipline', 'class': 'form-control', 'discipline-queries-url': reverse_lazy('ajax-load-discipline')}),
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.