[Answer]-Populating prefixed fields – bug or feature?

1πŸ‘

βœ…

The first parameter to the form is the input data, which is usually request.POST. If you render a Form with a prefix, you will see that all form html elements will have a prefixed name, for example <input name='yourprefix_text' /> etc. If you POST such a form to your Django app, the POSTed data will have the prefix, too.

So, if you are using a prefix, the input data needs to be prefixed, too:

f = InputForm({'yourprefix_column': c.id}, prefix='yourprefix')

Usually, it is a better idea to use the initial parameter to the form for default values, because otherwise the form is always bound, and this has some consequences, for example default/initial values for other fields are will not work.

f = InputForm(prefix='yourprefix', initial={'column': c})
# or ...
form_list = [InputForm(prefix=column.id, initial={'column': column})
             for column in col_list]

If you want to always set the column to a programatically determined value, and not allow the user to change it, it is better to not include the field in your form, and set the field manually after saving the object:

f = InputForm(request.POST)
if f.is_valid():
    instance = f.save(commit=False)
    instance.column = c
    instance.save()

To make your field hidden, you can change the widget, as described in the documentation:

class InputForm(ModelForm):
    class Meta:
        widgets = {
            'column': forms.HiddenInput,
        }
        # ...
πŸ‘€sk1p

Leave a comment