Skip to content Skip to sidebar Skip to footer

Passing Objects To A Django Form

I've found some similar questions, but not quite. I'm new-'ish' to Django, and trying to create a dynamic form, also without Models. I want to read a directory, find files of a t

Solution 1:

You have quite a few errors, and I'm surprised this runs at all, since self.txt is not defined at the class level where you reference it in CHOICES.

The reason you get the args error is that you are indeed not passing anything to the form when it is not a POST; that is, when you first visit the page to see the empty form. Actually, it's worse than that because you're not instantiating it at all; you need to use the calling parentheses in the else block.

Once you've fixed that, you will have the scope error I mentioned above. You need to set the choices in the __init__ method as well; you can define an empty default in the field and overwrite it. So:

classSelectForm(forms.Form):
    choices = forms.MultipleChoiceField(choices=(), widget=forms.CheckboxSelectMultiple())
    def__init__(self, *args, **kwargs):
        txt = kwargs.pop('txt_zip', None)
        super(SelectForm, self).__init__(*args, **kwargs)
        self.fields['choices'].choices = txt

defselect(request):
    txt_list = [fn for fn in os.listdir('/static/data/') if re.search(r'\.txt$', fn, re.IGNORECASE)]
    txt_zip = zip(txt_list, txt_list)

    if request.method == 'POST':

        form = SelectForm(request.POST, txt_zip=txt_zip)
        if form.is_valid():
            choices = form.cleaned_data.get('choices')
            # do something with your resultselse:
        form = SelectForm(txt_zip=txt_zip)
    ...

You might also consider moving the calculation of txt_list into the form __init__; that way you don't have to pass it in at all.

Post a Comment for "Passing Objects To A Django Form"