[Django]-Can you use a Django form multiple times in one view?

7👍

I haven’t run your code, but my best guess is that yes, it’s a problem with using the same form multiple times in the same view. The reason? All of your <input type="checkbox" name="..." ... /> tags will have the same name, 'dataType'. The user’s browser knows nothing of your back-end, and will just send, for example, dataType=on&dataType=on as POST data for the three fields if two are checked and one is not.

Seeing the problem here? How is django supposed to know which of those dataType fields are for your NOM, DDM, or RAW forms? It can’t know.

You should be able to solve this using form prefixes. In short, there’s a kwarg that you can pass to a form’s __init__() that will cause a prefix to be added to all of the form items in the rendered HTML. So, for example:

form_NOM = DataTypeForm(request.POST or None, section_label="ENG_NOM", 
                        initial_value=True, prefix="NOM")
form_DDM = DataTypeForm(request.POST or None, section_label="SCI_DDM",
                        initial_value=True, prefix="DDM")
form_RAW = DataTypeForm(request.POST or None, section_label="SCI_RAW", 
                        initial_value=False, prefix="RAW")

Hope that helps!

3👍

This is exactly what Django formsets are for. They allows you to create a set of the same type of form. It handles prefixes, and adds a management form so that Django doesn’t get confused as to what data comes from what form.

https://docs.djangoproject.com/en/1.8/topics/forms/formsets/

Leave a comment