Skip to content Skip to sidebar Skip to footer

Update Django Choice Field With Database Results

I am developing an application using django where the UI needs to be updated when user interacts with it. For instance I have a Drop down field where the user selects a drink and s

Solution 1:

   class MyForm(forms.Form):
          my_choice_field = forms.ChoiceField(choices=MY_CHOICES) 

So if you want the values to be dynamic(or dependent of some logic) you can simply modify your code to something like this:

either

  def get_my_choices():
   # you place some logic here 
     return choices_list
  class MyForm(forms.Form): 
     my_choice_field = forms.ChoiceField(choices=get_my_choices()) 

or

   User_list = [ #place logic here]
     class MyForm(forms.Form): 
     my_choice_field = forms.ChoiceField(choices=get_my_choices()) 

but once database value is updated, new data value will be popoulated only on restart of server. So write a function like this in forms:

   class MyForm(forms.Form):
         def __init__(self, *args, **kwargs):
                super(MyForm, self).__init__(*args, **kwargs)     
                self.fields['my_choice_field'] = forms.ChoiceField( choices=get_my_choices() )

or in place of the get_my_choices u can ad the USER_LIST too.


Solution 2:

If you have models for location and quantity, a ModelChoiceField should work:

class dform(forms.Form):
    location = forms.ModelChoiceField(queryset = Location.objects.all())

Otherwise, you'll need to query the database directly, for example:

class dform(forms.Form):
    location = forms.ChoiceField(choices = get_location_choices())

# elsewhere
from django.db import connection
def get_location_choices():
    cursor = connection.cursor()
    cursor.execute("select location_id, name from location_table")
    return cursor.fetchall()

The SQL query to use here depends on your database engine and table schema.


Solution 3:

I think that, based on my understanding of your question, the best solution would be to include JSON objects with your form and load these using jQuery instead of submitting the form over and over. Included in your form, you should add something like:

class MyForm(forms.Form):
    CHOICE_DICT = {
        'choice_1': [
            'option_1',
            'option_2',
        ],
        etc...

Then you should include form.CHOICE_DICT in your context, load that with jQuery, and render it depending on changes to other fields.


Post a Comment for "Update Django Choice Field With Database Results"