validation problems in inline admin form

1,404 views
Skip to first unread message

Wintoon

unread,
Sep 10, 2008, 11:19:51 AM9/10/08
to Django users
Hello,

I cant seem to figure out if this is working correctly:

In admin.py I put some code (end of message) to validate an inline
entry. The validation works just fine, however the error message is
not shown in the appropriate place inline. Is this a bug I should file
or is there something wrong with my implementation?



.....

class InlineForm(forms.ModelForm):
class Meta:
model = Inline
def clean(self):
if ...
raise forms.ValidationError('Error message here.')
return self.cleaned_data

class StuffInline(admin.TabularInline):
model = Inline
form = InlineForm
extra = 6

class FormAdmin(admin.ModelAdmin):
inlines = [StuffInline]
admin.site.register(Form, FormAdmin)

Munhitsu

unread,
Sep 28, 2008, 12:40:44 PM9/28/08
to Django users
Hi,
I have the same, so I've decided to live with the following
workaround.

Form.clean() is not reported properly for inlines but
Form.clean_<fieldname>() works fine.
In theory only Form.clean() is recommended for cross field validation
but in fact Form.clean_<fieldname>() can also refer to the other
fields.
However there is one condition. They all shall be defined prior to the
specific field in the model.
It's thanks to sequential processing of fields.
In such situation you can refer to them using cleaned_data hash. If
you need to refer to field which is defined later that there is data
hash but you'll end up in mess in case of Inlines.

Here goes the example. I hope it helps.

class UserProfile(models.Model):
"""
Place to store extra user information. Editable from Users.
"""
user = models.ForeignKey(User, verbose_name=_("User"),
unique=True)
price_variant = models.CharField(_('Price variant'),max_length=1,
choices=PRICE_CHOICES, default='R')
phone_number = models.CharField(_('Phone number'),max_length=20)
address_street = models.CharField(_('Address Street'),
max_length=30)
address_code = models.CharField(_('Address Code'),max_length=6)
address_city = models.CharField(_('Address City'),max_length=20)
address_state = models.ForeignKey(State)
address_country = models.ForeignKey(Country, default=1)
company_name = models.CharField(_('Company
name'),max_length=20,blank=True)
euvat = models.CharField(_('EU VAT'),max_length=16,blank=True)

class UserProfileAdminForm(forms.ModelForm):
class Meta:
model = UserProfile

def clean_euvat(self):
if self.cleaned_data["company_name"] and not
self.cleaned_data["euvat"].strip():
raise forms.ValidationError('Please provide EU VAT since
you have provided company name.')
# do something that validates your data
return self.cleaned_data["euvat"]


Regards,
Mateusz
Reply all
Reply to author
Forward
0 new messages