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


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.

Leave a comment