Whenever a specific business is selected from a dropdown list, I want to automatically populate a Django form field.
For example:
I have a list of businesses (business A, business B, ...) and corresponding countries where each business is located.
Business A --> France
Business B --> Germany
Business C --> England
In my form, selecting a business should immediately fill in the country field with the associated country. If the business changes, the country should change accordingly.
I am working with Django 1.11.18.
The scenario:
In my code, MemberState
represents the Country as shown above, and RBI
represents the business.
My Model:
class MemberState(models.Model):
name = models.CharField(max_length=256, verbose_name=_('Name'))
code = models.CharField(max_length=256, verbose_name=_('Code'))
class RBI(models.Model):
short_name = models.CharField(max_length=256, verbose_name=_('Short name'), unique=True)
member_state = models.ForeignKey(MemberState, verbose_name=_('Member State'))
...
My Form:
class FinalProductSearchForm(forms.Form):
releasing_body = ShortNameModelChoiceField(queryset=RBI.objects.filter(active=True).order_by('short_name'), required=False,
widget=forms.Select(), empty_label=_('Select'), label=_('Releasing Body/Institution'))
member_state = forms.ModelChoiceField(queryset=MemberState.objects.filter(active=True).order_by('name'), required=False,
widget=forms.Select(), empty_label=_('Select'), label=_('Member state'))
...
I aim to choose a releasing_body
in the form and auto-fill the associated member_state field. When switching the realeasing_body
, the corresponding member_state
should be loaded.
Although I tried some Django methods, I realize that AJAX requests are needed for this task - which is new to me.
Implementing AJAX:
My first attempt at implementing AJAX didn't work, here are the snippets:
In my views.py file, I added this function:
def ajax_member_state_request(request):
if request.is_ajax():
release_body = request.GET.get('releasing_body', None)
print(release_body)
member_state_ini = ReleaseBodyInstitution.objects.values_list('member_state', flat=True).get(id=release_body)
print(member_state_ini)
member_state = MemberState.objects.get(id=member_state_ini)
print(member_state)
return JsonResponse({'member_state': member_state})
In urls.py, I included:
url(r'^finalproduct/list/$', FinalProductListView.as_view(),
name='finalproduct-list'),
url(r'^finalproduct/list/ajax_member_state_request/$', views.ajax_member_state_request, name='ajax_member_state_request'),
Lastly, in my HTML file, I included:
<form id="providerForm" data-provider-url="{% url 'ajax_member_state_request' %}" class="navbar-search" method="GET" action="{{ url }}">
{% csrf_token %}
<div class="row">
<div class="col-md-5">
{{ search_form.releasing_body|as_crispy_field }}
</div>
<div class="col-md-5">
{{ search_form.member_state|as_crispy_field }}
</div>
</div>
<input type="submit" class="btn btn-default" value="{% trans 'Search' %}" />
<input type="button" class="btn btn-default" name="clear" value="Reset" onclick="clearForm(this.form);">
</form>
The AJAX section looks like this:
$("#id_releasing_body").change(function () {
var url = $("#providerForm").attr("data-provider-url");
var releasingBodyId = $(this).val();
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: {
'releasing_body': releasingBodyId
},
success: function (data) {
$("#id_member_state").val(data.member_state);
}
});
});