简体   繁体   中英

How to DYNAMICALLY pass values from template to views, and then receive them too?

I have a template with a drop down list and some text boxes. I want the values appearing in the text box to change dynamically based on what the user selects in the drop down. How can I implement them such that when the user selects an option in drop down, corresponding data from database gets fetched and appears in those text boxes?

Here is a simple example:

html

<select>
  <option val="mercedes">Mercedes</option>
  <option val="toyota">Toyota</option>
</select>

js

$('select').change(function (e) {
  e.preventDefault();
  var car = $(this).val();

  $.ajax({
    method: "GET",
    url: "{% url 'car_data' %}",
    data: {"car": car}
  }).done(function (response) {
    console.log(response)  // Do whatever you want with the response
  }).fail(function (err) {
    console.log(err)
  })
})

view

def get_car_data(request):
    car = request.GET['car']
    car_obj = CarData.objects.get(car=car)

    data = {"car_details": car_obj.details}  # If .details exists of course
    return JsonResponse(data)

urls

urlpatterns = [
    ...
    path('car-details', views.get_car_data, name="car_data"),
    ...
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM