models.py
class Image(models.Model):
title = models.CharField(max_length=255)
image = models.ImageField(upload_to='attack_images', blank=True, null=True)
source_url = models.URLField(blank=True,null=True)
domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True)
creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True)
slug = models.SlugField(blank=True,null=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)[:50]
if self.source_url and not self.image:
result = urllib.request.urlretrieve(self.source_url)
self.image = os.path.basename(self.source_url), File(open(result[0], 'rb'))
if self.source_url:
if '//' in self.source_url:
d = self.source_url.split('//')[1].split('/')[0]
else:
d = self.source_url.split('/')[0]
try:
domain = Domain.objects.get(domain_url=d)
except Exception as e:
print(e)
domain_object = Domain.objects.create(domain_url=d)
domain = domain_object
self.domain = domain
return super(AttackImage, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse("attack_image_detail", kwargs={
'pk': str(self.id),
'slug': str(self.slug)})
I believe this happens because of the line self.image = os.path.basename(self.source_url), File(open(result[0], 'rb'))
Can anyone help with this? Thanks in advance. Stack is python/django. My basic question is, if I am correct, and the line above is what is causing the problem, how do I assign an image to an ImageField properly (without saving it)?