update django choice field with database results

人走茶凉 提交于 2020-01-05 12:15:27

问题


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 submits it then based on that a dropdown with the places that drink is available, price and quantity at each place needs to be displayed. The user will then further submit the form for second process.

From my understanding the Forms in django are pre-defined and I am not able to think of a way using which I could achieve this.

What I could come up was defining a regular form class

class dform(forms.Form):
    SOURCES_CHOICES = (
              (A, 'A'),
              (E, 'E'),
              )
  drink = forms.ChoiceField(choices = SOURCES_CHOICES)
  location = forms.ChoiceField(choices = **GET THIS FROM DATABASE**)
  quantity = forms.ChoiceField(choices = **GET THIS FROM DATABASE**)
  .
  .
  .

My view is like,

def getdrink():
   if request.method == 'POST':
      #code for handling form
      drink =  dform.cleaned_data['drink']
      #code to get values from database

I have no idea how to generate or populate or append the values i get from the database to the choicefield in my form. I did try looking up on SO but none of the solutions here explained properly how to do it. Also, due to certain requirements I am not using the models. So my database is not at all related to the models.

I am at a total loss Please help me out


回答1:


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.




回答2:


   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.



来源:https://stackoverflow.com/questions/24877686/update-django-choice-field-with-database-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!