Reputation: 15040
Consider we have a model with a BinaryField
:
from django.db import models
import hashlib
class Target(models.Model):
# ...
image = models.BinaryField(max_length=(1<<24)-1)
# ...
def __str__(self):
return hashlib.md5().update(self.image).hexdigest()
Does the above code compute correctly the MD5 digest of the image?
Or is there some method or variable inside BinaryField
to get the memory to pass to the update()
method?
UPDATE: When I try:
>>> from pathlib import Path
>>> t = Target(image=Path('../../Experiments/LoginError2.jpg').read_bytes())
>>> t
I'm getting the following error:
AttributeError: 'NoneType' object has no attribute 'hexdigest'
So what am I doing wrong?
Upvotes: 0
Views: 2173
Reputation: 15040
So here's the conclusion: BinaryField
can be assigned bytes and can be read as bytes.
In the above code the hashing was done wrongly, and the correct way is:
hashlib.md5(self.image).hexdigest()
Upvotes: 0
Reputation: 21779
In regard to your update about the AttributeError
, you're calling the hexdigest()
method incorrectly.
The thing is, update()
method returns None
, and you're pretty much trying to call hexdigest()
on None
. Chaining method calls like this only works if the previous method returns an actual object instead of None
.
You'll have to do this call in multiple steps:
def __str__(self):
m = hashlib.md5()
m.update(self.image)
return m.hexdigest()
Upvotes: 1