Opened 5 years ago

Closed 5 years ago

#13763 closed (invalid)

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

Reported by: marktranchant 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: UI/UX:

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 Changed 5 years ago by marktranchant

  • Component changed from Uncategorized to Forms
  • Keywords modelform prefix validation is_valid added
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

comment:2 Changed 5 years ago by marktranchant

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

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

comment:3 Changed 5 years ago by kmtracey

  • Resolution set to invalid
  • Status changed from new to closed

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