Opened 10 years ago

Closed 10 years ago

#13763 closed (invalid)

Setting prefix on a ModelForm causes is_valid() to return False

Reported by: Mark Tranchant Owned by: nobody
Component: Forms Version: master
Severity: Keywords: modelform prefix validation is_valid
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Setting the prefix attribute on a ModelForm causes is_valid() to always return False. I can't find anything in the docs that refers to this behaviour. I am bundling multiple ModelForms into a single HTML form, so I'm using the prefix. On submission, I bind each of the ModelForms to their bit of the POST data to process them. If I set the prefix (in case validation fails and I need to re-display) *before* the call to is_valid(), that call always fails.

Here's a quick test case using lightly-simplified versions of my real classes:

class RptTField(models.Model):
        report = models.ForeignKey(Rpt)
        config = models.ForeignKey(RptCfgTField)
        text = models.TextField()

class RptTForm(forms.ModelForm):
        class Meta:
                model = RptTField
                exclude = ('report','config')

>>> from myproj.models import *
>>> a = RptTForm({'text':'hello world'})
>>> a.prefix
>>> a.is_valid()
>>> b = RptTForm({'text':'hello world'},prefix='abc')
>>> b.prefix
>>> b.is_valid()

This is using the latest SVN release, 13353.

Change History (3)

comment:1 Changed 10 years ago by Mark Tranchant

Component: UncategorizedForms
Keywords: modelform prefix validation is_valid added

comment:2 Changed 10 years ago by Mark Tranchant

Having failed validation, the error message complains that the field is not set:

>>> b.errors
{'text': [u'This field is required.']}

comment:3 Changed 10 years ago by Karen Tracey

Resolution: invalid
Status: newclosed

When you set the prefix, it must also then be included in the data dictionary keys.

>>> from ttt.models import Parent
>>> from django import forms
>>> class PForm(forms.ModelForm):
...     class Meta:
...         model = Parent
>>> pf = PForm({'name': 'a'})
>>> pf.is_valid()
>>> pf = PForm({'name': 'a'}, prefix='xyz')
>>> pf.is_valid()
>>> pf.errors
{'name': [u'This field is required.']}
>>> pf = PForm({'xyz-name': 'a'}, prefix='xyz')
>>> pf.is_valid()
Note: See TracTickets for help on using tickets.
Back to Top