Opened 15 years ago

Closed 15 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: dev
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

Description

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()
True
>>> b = RptTForm({'text':'hello world'},prefix='abc')
>>> b.prefix
'abc'
>>> b.is_valid()
False

This is using the latest SVN release, 13353.

Change History (3)

comment:1 by Mark Tranchant, 15 years ago

Component: UncategorizedForms
Keywords: modelform prefix validation is_valid added

comment:2 by Mark Tranchant, 15 years ago

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

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

comment:3 by Karen Tracey, 15 years ago

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()
True
>>> pf = PForm({'name': 'a'}, prefix='xyz')
>>> pf.is_valid()
False
>>> pf.errors
{'name': [u'This field is required.']}
>>> pf = PForm({'xyz-name': 'a'}, prefix='xyz')
>>> pf.is_valid()
True
>>>
Note: See TracTickets for help on using tickets.
Back to Top