[Fixed]-How to check for uniqueness in the derived field of model in Django

1๐Ÿ‘

โœ…

I think what you need is a custom form. You can validate whatever you want in clean_<field> method of your form. It should be similar to this:

class InfoFromFileForm(ModelForm):
    def clean_File(self):
        file_obj = self.cleaned_data['File']
        hash = get_hash() # whatever you use to get file hash
        if InfoFromFile.objects.filter(file_hash=hash).exists():
            raise ValidationError(_("The hash must be unique.")
        return file_obj

Then in your admin class

class InfoFromFileAdmin(admin.ModelAdmin):
    # your things
    form = InfoFromFileForm
    # more things
๐Ÿ‘คKarolis Ryselis

Leave a comment