Django FormView and Gettting Select Value

Hei All,

I normally develop with DRF, but today I’m wanting to call a method based on a chosen option from an HTML select on a form I’ve made with forms.Form.

I think I’ve done most things correctly, but I don’t seem to be able to get the value from the select field in my view using kwargs.

Here is my view

class ImporterView(FormView):
    template_name = "importer.html"
    form_class = ImporterForm

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)

        if form.is_valid():
            result = web_importer(kwargs.get('species'))
            return HttpResponse(result)
        return self.form_invalid(form)

When I print result I get None

And here is my Form

SPECIES_CHOICES = [
    ('rabbit', 'Rabbit'),
    ('dog', 'Dog'),
    ]


class ImporterForm(forms.Form):
    species = forms.CharField(
        label='Select Species',
        widget=forms.Select(choices=SPECIES_CHOICES)
    )

I’m trying to work out where I’ve gone wrong, why I’m getting None when accessing kwargs and where should I look in order to get a better understanding for working with more custom FormViews and interactions?

Cheers,

C

This select field is in the form, so it won’t be in **kwargs. It comes in request.POST, with which you’re initializing your form. So assuming the form is clean, form.cleaned_data[‘species’] will have the response from the form.

1 Like

Hi Ken,

Thank you. I completely interpreted that doc the wrong way. Mistook it for applying to a ModelForm.

Again, you’ve saved my day. Thank you very much and thank you for all your contributions here.

Cheers,

C