简体   繁体   中英

In Python Django, how do I assign a charfield to a column in SQL based on the user's selection from a combobox?

First time caller here. The title essentially describes by question. I'm creating an application for work. They are requesting a form field which can be dynamically assigned to a column in a SQL table with a selection from a combobox.

As an example, say we have a table named "Groceries". In the "Groceries" table, there are 3 columns named "Dairy", "Produce", and "Deli". On a webpage, there is a charfield with an associated combobox. The combobox has "Dairy", "Produce", and "Deli" as choices. When the user submits text in the charfield it will populate whichever column in the database the user chooses from the combobox.

How do I do this? Unless I am asking the wrong question, I found something that doesn't exist in Google yet.

Thanks

That's pretty easy. You use normal form with 2 fields, one is the combobox the other is the char field:

class GroceryForm(forms.Form):
    grocery_type = forms.ChoiceField(choices=(('dairy', 'Dairy'),
                                              ('produce', 'Produce'),
                                              ('deli', 'Deli')))
    name = forms.CharField()

Then in views.py:

def blah_method(request):
    form = GroceryForm(request.POST or None)
    if form.is_valid():
        grocery_type = form.cleaned_data['grocery_type']
        if grocery_type == 'dairy':
            result = Groceries.objects.create(dairy=form.cleaned_data['name'])
        elif grocery_type == 'produce':
            result = Groceries.objects.create(produce=form.cleaned_data['name'])
        elif grocery_type == 'deli':
            result = Groceries.objects.create(deli=form.cleaned_data['name'])

It's not tested, but you should get the general idea.

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