Django:管理员更改形式

时间:2018-03-29 08:16:16

标签: django django-admin

我正在开发一个webapp,用户可以成为一个(也是唯一一个)组织的成员 - 这是通过Profile模型中的外键来完成的,后者又具有一对一的链接使用默认的django.auth.user模型。我们还希望确保每个电子邮件地址仅在每个组织中使用一次。为此,我们将以下函数添加到Profile模型中:

    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()

但是,当我使用重复的电子邮件地址通过Django admin添加用户时,所有显示的内容都是表单顶部的通用please fix the errors below消息。电子邮件字段附近不显示任何文本,并且根本不显示ValidationError文本 - 因此管理员无法获知实际出错的信息。

有谁知道为什么ValidationError消息没有显示在管理员中,我们可以采取哪些措施来纠正这个问题?

我们正在使用标准ModelAdmin

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')  

2 个答案:

答案 0 :(得分:1)

ProfileAdmin 类中提升find。例如,来自find /var/www/html/test -type f -newermt $(date +%F) 方法。

答案 1 :(得分:1)

我认为在这种情况下,表单验证是一个好主意。

<强> 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')

admin.py

class YourAdminClass(admin.ModelAdmin):
     form = YourForm
相关问题