2

I want to create a dynamic html form Select Dropdown List using data from JSON url from DJANGO model.I want that Select Dropdown List to be update dynamic without the user need to refresh the page to get last changes from json url.

for example if some other user add new entry in django table then that Dropdown List update automatically without need refresh page.

but in my code the user need refresh the page to get last changes

any idea who to avoid refresh page to get data ?

here the code :

views.py

def test_json(request):
    response_data=serialize('json',andress.objects.all())
    return HttpResponse(response_data,content_type='json')

urls:

url(r'^test_data/$', test_json, name='test_json'),

json link :

[
{
model: "log.mymodel",
pk: 3,
fields: {
f1: "some vasa",
f2: "some vadada",
f3: "some vsasa",
}
},
{
model: "log.mymodel",
pk: 4,
fields: {
f1: " some v1",
f2: "some v2",
f3: "some v3",
}
}
]

html page :

<select id="locality-dropdown" name="locality">
</select>

<script>
let dropdown = document.getElementById('locality-dropdown');
dropdown.length = 0;
let defaultOption = document.createElement('option');
defaultOption.text = 'Choose State/Province';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
const url = 'http://127.0.0.1:8000/test_data/';
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
  if (request.status === 200) {
    const data = JSON.parse(request.responseText);
    let option;
    for (let i = 0; i < data.length; i++) {
      option = document.createElement('option');
      option.text = data[i].pk;
      option.value = data[i].pk;
      dropdown.add(option);
    }
   } else {
    // Reached the server, but it returned an error
  }   
}
request.onerror = function() {
  console.error('An error occurred fetching the JSON from ' + url);
};
request.send();
</script>
Mar
  • 683
  • 2
  • 11
  • 26
  • 1
    You would need to be frequently checking for any update, you can use javascript ```setInterval``` to make an ajax call every X minutes: https://stackoverflow.com/a/4930470/11193405 – p14z Apr 10 '19 at 18:50
  • @Pedro where is the right place in my script to put that function ? setInterval(function() { //your jQuery ajax code }, 1000 * 60 * X); // where X is your every X minutes – Mar Apr 10 '19 at 18:59
  • I would first put your JavaScript code in a function so it can be called many times. Then make the function call where it says ```//your jQuery ajax code```. – p14z Apr 10 '19 at 19:10
  • @Pedro thank you the setInterval working but I am not sure if I like this because if I use small x minute any time update values close/open again – Mar Apr 10 '19 at 20:28
  • do you mean that the selected option gets unselected? That can be solved with some lines of code – p14z Apr 10 '19 at 21:04
  • @Pedro i cant explain,any time where the code reloading then show/unshow the list with values – Mar Apr 10 '19 at 21:12

1 Answers1

1

I just implemented this in a couple places using the ModelSelect2Widget from django-select2. Because the JSON requests to the server happen when the user types in the select element, those requests always use most recent version of the JSON view.

You can update your view to an AutoResponseView, then use it in a form with a ModelSelect2Widget:

from django_select2.forms import ModelSelect2Widget

class MyForm(forms.Form):
    my_field = forms.ChoiceField(
        widget=ModelSelect2Widget(
            data_url='test_json'  # this is a URL name that gets resolved
        )
    )
Franey
  • 4,164
  • 2
  • 16
  • 18
  • its the first time to I saw this packages,but in the data_url='test_json' how field keep ?can you show me a complete example with my post code ?thank you – Mar Apr 10 '19 at 20:30