Jasper
Jasper

Reputation: 2231

Django: ValidationError message not showing in admin changeform

I am working on a webapp where user can be a member of one (and only one) organisation - this is done with a foreignkey in the Profile model, which in turn has a one-to-one link with the default django.auth.user model. We also want to make sure that each email address is only used once within each organisation. To do this we added the following function to the Profile model:

    def clean(self):
      if self.organisation and Profile.objects.filter(
            user__email=self.user.email,
            organisation_id=self.organisation.id
            ).exists():
        raise ValidationError({'user': _('The email address from this user is already used within this organisation!')})
      return super(Profile, self).clean()

However, when I add a user through the Django admin using an duplicate email address all that gets displayed is a generic please fix the errors below message at the top of the form. No text is displayed near the email field and the ValidationError text isn't displayed at all - thus giving the admins no information on what actually went wrong.

Does anyone know why the ValidationError message isnt being displayed in the admin, and what steps we can take to rectify this?


We are using a standard ModelAdmin class

class ProfileAdmin(ModelAdmin):

  def username(self, profile, **kwargs):
      return u'{} ({})'.format(
          profile.user.profile.full_name(),
          profile.user.username)

  search_fields = ['user__username', 'user__first_name', 'user__last_name', 'user__email']
  list_display = ('username', 'organisation')
  list_filter = ('organisation')  

Upvotes: 1

Views: 277

Answers (2)

Nitheesh MN
Nitheesh MN

Reputation: 628

I think form validation is a good idea in these type of situations.

forms.py

class YourForm(forms.ModelForm):

    def clean(self):
        super(YourForm, self).clean()
        data1 = self.cleaned_data.get('data1')
        data2 = self.cleaned_data.get('data2')

        # Add validation condition here
        # if validation error happened you can raise the error 
        # and attach the error message with the field you want.

        self.add_error('field_name', 'error message')

In admin.py

class YourAdminClass(admin.ModelAdmin):
     form = YourForm

Upvotes: 1

miksyn
miksyn

Reputation: 93

Raise ValidationError from ProfileAdmin class. For example, from clean_<field name> method.

Upvotes: 1

Related Questions