简体   繁体   中英

Send JavaScript value to method on views.py (Django)

I'm using django (4.0.4) to develop a 'simple' interface with three dropdown list with the data of the last two depends of the value selected of the first.

This is the front:

在此处输入图像描述

This is the project structure dir:

├── db.sqlite3
├── manage.py
├── example_web
│   ├── asgi.py
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── web
    ├── admin.py
    ├── apps.py
    ├── __init__.py
    ├── migrations
    ├── models.py
    ├── static
    │   ├── css
    │   │   └── style.css
    │   └── js
    │       └── app.js
    ├── templates
    │   ├── index.html
    ├── tests.py
    └── views.py

This is urls.py

from django.contrib import admin
from django.urls import path
from web.views import homePageView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', homePageView),
]

views.py

from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from jf.clients import RPClient




def homePageView(request):

    a = _get_coaches()
    b = _get_devices()
 
    value_js = request.GET.get('id')
    print(value_js)

    context = {
        'coaches': a,
        'devices': b,

    }

    return render(request, 'index.html', context)
 

def _get_coaches():
    client = RPClient('dev', proxy_ip='10.10.1.15')
    a = client.get_current_value('status/coach')

    return [i['id'] for i in a['items']]


def _get_devices(request):
    client = RPClient('dev', proxy_ip='10.10.1.15')
    a = client.get_current_value('status/cable/X')
    
    # !!!!!!!!!!

    # HERE is where in the X place I want to store the value_js variable 

    return [i['id'] for i in a['items']]

This is the js, css and html

 function value_id() { coach_id = document.getElementById("coaches").value; window.alert('ID Selected: ' + coach_id); $.ajax({ type: "POST", url: '', data: { 'id': coach_id } }) }
 body { background: #fafafa; font-size: 1.25em; font-family: 'Raleway', sans-serif; } h1 { text-align: center; font-size: 48px; margin-top: 50; margin-bottom: 50; } section { width: 100%; min-height: 100vh; display:inline-block; justify-content: left; align-items: flex-start; background: #fafafa; padding-left: 180; margin-top: 250; width: 225px; } div { position: fixed; } select option:hover { margin: 40px; background: #4780D5; color: #fff; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.4); } .selectColor { position: relative; padding: 10px; background: #fafafa; border: none; outline: none; width: 200px; border-radius: 4px; box-shadow: 0 15px 25px rgba(0, 0, 0, 0.1); } .header { position: fixed; width: 100%; background-color: #4780D5; top: 0; left: 0; color:#fafafa; opacity: 0.8; }
 {% load static %} <title>Website</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script src="{% static 'js/app.js' %}"></script> <html> <body> <div class="header"> <h1>Example</h1> </div> <div> <section> <select id='coaches' class="selectColor" onchange="value_id()"> <option value="">Select Coach</option> {% for coach in coaches%} <option id='test' value="{{ coach }}">Coach {{coach }}</option> {% endfor %} </select> </section> <section> <select id='devices' class="selectColor" onchange="value_device()"> <option value="">Select Device</option> {% for device in devices%} <option style="text-transform:uppercase;" value="{{ device }}">{{ device }}</option> {% endfor %} </select> </section> </div> </body> </html> {% block page_content %}{% endblock %}

The first dropdown is autocompleted by making a get request to an endpoint like /status/coach and I get the ID.

So the first dropdown list would look something like this:

  • Coach 1
  • Coach 2
  • Coach 3

I need the second dropdown to also make a get request to the same endpoint adding the id it picks up after at the end, ie if I select on the dropdown elements 'Coach 2' the enpoint will be /status/coach/2

But I don't know how to send the value of the id that I store in coach_id on js file and to a method in the views file.

According to examples that I have read here they proposed two things: send this variable with ajax (I've never been using js until this moment so there are probably things that are wrong) but when I try this I always get None as a value of the 'coach_id' variable and only appears when I reload the page on the django debug, not appears when I select an item from the list, only the window.alert is working...what I am doing wrong?

Another alternative I have seen is to put the section and select tag sctructure inside a form , like this , but I don't want a post button with a form

So...how can I send the ID value of the selected car to the views file on get_devices() method?

Thanks!

You can pass this as the argument to the onchange call and in javascript you can get this as element.

<select id='coaches' class="selectColor" onchange="value_id()">

In javascript

function value_id(thisValueElement) {
 const value = thisValueElement.value
 
 const endpoint = "{% url 'your_homepage_view_url' %}
 fetch(endpoint + "?coach_id=" + value)
  .then(res => res.json())
  .then(response => { 
    // Return JsonResponse from server and get the value here.
  })
}

And then in your view you get that from the GET request.

def homePageView(request):
    coach_id = request.GET.get("coach_id", default_id_here_if_not_omit_this)
    a = _get_coaches()
    b = _get_devices()
 
    value_js = request.GET.get('id')
    print(value_js)

    context = {
        'coaches': a,
        'devices': b,

    }

    return render(request, 'index.html', context)

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