How to fill the form field with the data based on drop down selection of another form field using ajax request

14 views
Skip to first unread message

Dilipkumar Noone

unread,
Feb 8, 2020, 3:39:46 AM2/8/20
to Django users
Dear group,

I am Django learner.

I have two models.

1. ModelRegister 
2. ModelGSP

ModelRegister returns model_name.
ModelGSP has a foreignkey to ModelRegister.

When we select a particular model from a ModelGSP model,i want to fill a field in ModelGSP with the data for a selected model when ajax request is made.

Input data and expected result shown in screen shot below.

currently when i select any model from RegisteredModel, none of the data is populated in get_model_nos_for_modelname field.

Please correct me if i am doing any mistake and how to proceed further.

query.png

Below is my code snippet :

Enter code here...

Models.py:

=======
class ModelRegister(models.Model):
    """
        This class is used to register the model.
    """
    FLOAT_CHOICES = [[float(x), float(x)] for x in range(1, 21)]

    model_name = models.CharField(max_length=128, verbose_name="ModelName")
    model_no = models.CharField(max_length=128, verbose_name="ModelNo")
    os_name = models.ForeignKey(OSName, on_delete=models.CASCADE, verbose_name="OSName",default=" ")
    chipset_type = models.ForeignKey(ChipsetType,on_delete=models.CASCADE, verbose_name="chipsetType")

    class Meta:
        verbose_name_plural = "ModelRegisteredList"

    def __str__(self):
        return self.model_name


class ModelGSP(models.Model):
    """
        This class is used to raise Model GSP request.
    """

    registered_model = models.ForeignKey(ModelRegister,on_delete=models.CASCADE, verbose_name="ModelName")
    model_nos_for_reg_model = models.ManyToManyField(ModelNumber)
    model_gsp_requester = models.CharField("Model GSP Requester", max_length=128,default=" ")
    integrator = models.CharField("Integrator", max_length=100,default=" ")

    class Meta:
     verbose_name_plural = "ModelGSPRequests"

    def __str__(self):
     return self.model_gsp_requester + self.integrator + str(self.pk)

class ModelRegisterForm(ModelForm):
"""
This class is used to register the model information.
"""

class Meta:
model = ModelRegister
exclude = ['model_leader']
#fields = '__all__'


@property
def helper(self):
helper = FormHelper()
helper.form_tag = 'model_register_form'
helper.layout = Layout(
Fieldset(
'Registered Model Details',
#Row('model_leader' ),
Row('model_name','model_no'),
Row('os_name', 'os_version'),
Row('chipset_type','chipset_name')
)
)

return helper

class ModelGSPRequestForm(ModelForm):
"""
This class is used to define the form fields to raise the model GSP request.
"""
registered_model = forms.ChoiceField(required=False,choices=unique_values)
#model_nos_for_reg_model = forms.ModelMultipleChoiceField(required=False,queryset=)

class Meta:
model = ModelGSPRequest
exclude = ['model_gsp_requester']

#choices=[]
def __init__(self, *args, **kwargs):
super(ModelGSPRequestForm, self).__init__(*args, **kwargs)
#self.form_tag = False
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset("Add Model GSP Request",
Row('registered_model','model_nos_for_reg_model')
)
)
self.fields['model_nos_for_reg_model'].queryset = ModelNumber.objects.none()

ajax.py:
========
def load_model_details(request):
print("load model details")
print("request method",request.method)

model_name_id = request.GET.get("model_name")
model_registered_instances = ModelRegister.objects.filter(model_name_id=model_name_id)

model_number = []

for model in model_registered_instances:
model_number = model_number.append(model.model_no)
print("Model Number:", model_number)


return render(request, 'model_info_options.html', {'model_registered_instances':model_registered_instances})

model_info_options.html:
========================
<!DOCTYPE html>
<html lang="en">
<option value="">---------</option>
{% for model in model_registered_instances %}
<option value="{{ model.pk }}">{{ model.model_no }}</option>
{% endfor %}
</html>

ModelGSP.html:
=============
<!DOCTYPE html>
{% extends 'base.html' %}
{% load crispy_forms_tags %}

{% block static %}
{% endblock static %}

{% block content %}
<form class="form" form='model_gsp_form' id="gspmodelinfoForm" method="post" model-details-url="{ %url 'ajax_load_model_details' %}" role="form">
{% csrf_token %}
<div class="container">
{% crispy form %}
<br>
<br>
<button type="submit" class="btn btn-primary">
{% if action == "add" %}
<span class="fas fa-plus"></span>Add
{% else %}
<span class="fas fa-edit"></span>Update
{% endif %}
</button>
<button type="reset" class="btn btn-primary" aria-label="Close" data-dismiss="modal">
<span aria-hidden="true">&times;</span>Cancel
</button>
</div>
</form>
{% endblock content %}

{% block scripts %}
<script type="text/javascript">
$(document).ready(function(){
$("#id_registered_model").change(function () {

var url = $("#gspmodelinfoForm").attr("model-details-url"); # Get the url of the 'gspmodelinfoForm' view

var model_name_id = $(this).val(); //get the selected model name id from the HTML input

$.ajax({ //Initialize an ajax request
url: url, //Set the URL of the request

data: {
'model_name' : model_name_id // add the model name to the GET parameters
},

success: function(data) { // 'data' is return of 'load_model_details' view function
$(#"id_registered_model_no").html(data) // place the contents of the model no with the data came from server
}
});
});
});
</script>
{% endblock scripts %}

def create_model_gsp_request_form(request,id=None):
print("create_model_gsp_request_form:", id)

if id:
action = 'edit'
model = get_object_or_404(ModelGSPRequest, pk=id)
else:
action = 'submit'
model = ModelGSPRequest()

message = ""

if request.method == 'POST':
print("when the request is POST ,In ModelGSPRequestForm")
form = ModelGSPRequestForm(request.POST, instance=model)

if form.is_valid():
new_model_gsp_request = form.save(commit=False)
new_model_gsp_request.model_gsp_requester = request.user.username
new_model_gsp_request.save()
form.save_m2m()
return HttpResponseRedirect('/gspapp/ModelGSPRequestList')

else:
print("when the request is GET ,In ModelGSPRequestForm")
form = ModelGSPRequestForm(instance=model)
# apply_gsp_model_data = serializerModelGSPRequestLists.serialize("json", ApplyGSP.objects.all())
# print("apply_gsp_model_Data:",apply_gsp_model_data)

context = {'form': form, 'Message': message, 'action': action}

context = {'form': form, 'Message': message, 'action': action}
return render(request, 'ModelGSP.html', context)

urls.py:
-------
urlpatterns = [
path('ModelGSPRequestList/', login_required(views.ModelGSPRequestList.as_view(), login_url='/gspapp/login/'), name='ModelGSPRequestList'),
path('ModelGSPRequestList/requestForm/', views.create_model_gsp_request_form, name='ModelGSPRequestForm'),
re_path(r'^editModelGSPRequest/(?P<id>\d+)/$', views.create_model_gsp_request_form, name='editModelGSPRequest'),
#path('',include(router.urls)),
path('ajax/load_model_details/', ajax.load_model_details,name='ajax_load_model_details')]

Regards,
N.Dilip kumar.




Reply all
Reply to author
Forward
0 new messages