1

I have a Django model where I want to auto-populate an md5 of another field on a custom save. It works fine until there's a duplicate value entered in the Admin, I'm getting a 50x error thrown rather than a Duplicate Error message. I expected the unique=True on the md5 field to check and catch this. Instead, I get the database unique constraint error. Feels like I'm missing something obvious but am perplexed. Is there someplace higher than save I should be checking this? Tried the pre_save signal, but had the same result.

class MailList(models.Model):
    email = models.CharField(max_length=400, null=False, blank=False)
    md5 = models.CharField(max_length=32, null=False, blank=True, unique=True)

    def save(self, *args, **kwargs):
        self.md5 = md5(self.email.strip().encode('UTF-8').lower()).hexdigest()
        super(MailList, self).save()

class MailListAdmin(admin.ModelAdmin):
    readonly_fields = ('date_entered', 'date_modified', )
    list_display = ('email',
                    'date_entered', 'date_modified', 'md5',
                    'subscriber', )
    save_on_top = True
    search_fields = ['email', ]

admin.site.register(MailList, MailListAdmin)
rgacote
  • 408
  • 2
  • 10

1 Answers1

0

Have you excluded the md5 field in your admin view? That might be your problem as md5 doesn't get checked for uniqueness in your view and it throws the 50x error. If that's the case, you can use a custom form for your ModelAdmin and check the md5 field there.

kaveh
  • 2,046
  • 1
  • 21
  • 33
  • md5 does appear in the Admin. Edited the original question to show the Admin configuration. – rgacote Dec 18 '14 at 20:55
  • Sorry, my bad; it's not about excluding the field, cause you're setting the value in the save method. – kaveh Dec 18 '14 at 21:38
  • Still, you can use a custom form and generate your md5 in its clean method and catch the error there rather than doing it in the save method. – kaveh Dec 18 '14 at 21:50
  • Thanks, I'd not done a custom admin form before. This StackOverflow had good directions for adding the custom form: http://stackoverflow.com/questions/10040442/override-a-form-in-django-admin – rgacote Dec 22 '14 at 15:04
  • And for clarification, in order to insert data so that the unique check will automatically work, the data needs to be inserted in the __init__ section of the form: http://stackoverflow.com/questions/7117012/modify-data-incoming-to-django-form-before-cleaning – rgacote Dec 22 '14 at 16:16
  • I have this problem too. Why is this post marked as accept solution? Where is the solution here? A custom form? – spinkus Sep 15 '16 at 12:34
  • @rgacote: yep, a custom form which validates md5 – kaveh Sep 15 '16 at 15:22