0

After I submit a form, I want to keep the value the user selects in the drop down field. I'm using Django 1.8. Some posts here alude to ways to do it with PHP by accessing the session variable:

Keep values selected after form submission

Is there a way to do this with Django? Maybe a JavaScript solution would work, but I am not too familiar w/ JS other than modifying and tooling around with existing JS code.

Community
  • 1
  • 1
mk8efz
  • 1,374
  • 4
  • 20
  • 36
  • What do you want to do with the value after it's selected? Are you talking about having it populated after the `save()` method, or to use in another part of the form? – jape Aug 09 '16 at 18:37
  • Literally nothing, I just want it populated after the user submits the form. They are picking which DB they want to search with that field, and if their search comes up empty, they have to reselect the DB and try another search term. Rarely do they have to switch up the DB, so I want it preselected with their last selection when the page reloads. – mk8efz Aug 09 '16 at 18:39
  • Is their selection saved in a model field? If it is, you can change your form's `__init__()` method to show the pre-populated data. Each time the form is saved, that field will get updated and show the latest selection. – jape Aug 09 '16 at 18:46
  • If you're using Django forms this should be done for you automatically. If you post your current code, maybe we can see what the issue is – Written Aug 09 '16 at 18:50

2 Answers2

0

Depending on how sensitive the information is, you could store them in localStorage as you submit the form and simply get the information back from localStorage when the page refreshes. One thing to keep in mind is that localStorage only stores strings, so if you want to store javascript objects you can use json.

Saving a string:

localStorage.setItem("key", "stringValueBeingStored");

Saving an object:

localStorage.setItem("key", JSON.stringify(objectBeingStored));

Retrieving stringValue:

var stringValue = localStorage.getItem("key");

Retrieving object:

var retrievedObject = JSON.parse(localStorage.getItem("key"));

Hope that helps!

Duly Kinsky
  • 996
  • 9
  • 11
0

The "Django way to do it" is probably adding a field in the User model called something like database (or whatever you want), and store which database the user has selected in there.

Arctic Tern
  • 64
  • 1
  • 1
  • 11