Python Forum

Full Version: How to save uploaded image url in database from Django?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
(Jul-04-2018, 11:18 AM)gontajones Wrote: [ -> ]I made a mistake.

In your model the field must be something like:
image_url = models.CharField(max_length=200)
Why are you doing this?
image_url = forms.CharField(widget=forms.HiddenInput())
image_url = '' # <- This

I have removed this line-
image_url = ''

So now I have changed in models.py like below-
class Brand(models.Model):
    name = models.CharField(max_length=60)
    description = models.TextField(blank=True, null=True)
    image_url = models.CharField()
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True)

    @property
    def logo(self):
        return get_logo(self.name, 'brand')

    class Meta:
        managed = False
        db_table = 'brand'

    def __str__(self):
        return self.name

new_brand = Brand()
new_brand.image_url = new_brand.logo('brand')
new_brand.save()
In this line-
new_brand.image_url = new_brand.logo('brand')
I am getting error-
Error:
new_brand.image_url = new_brand.logo('brand') TypeError: 'SafeText' object is not callable
What about this:

class Brand(models.Model):

    name = models.CharField(max_length=60)
    description = models.TextField(blank=True, null=True)
    image_url = models.CharField()
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True)

    @property
    def logo(self, folder):
        logo_name_with_ext = '{}{}'.format(self.name, '.png')
        self.image_url = '{}/{}'.format(IMAGE_PATH, os.path.join(folder, logo_name_with_ext))
        return mark_safe('<img src="{}" height="20" />'.format(logo_url))

    class Meta:
        managed = False
        db_table = 'brand'

    def __str__(self):
        return self.name


new_brand = Brand()
new_brand.name = "Brand Name"
new_brand.description = "Brand Description"
html_img_tag = new_brand.logo('brand')
new_brand.save()
same error-
Error:
html_img_tag = new_brand.logo('brand') TypeError: 'SafeText' object is not callable
I think that the @property is causing this.
I can't test it right now. Later I'll test it to figure out how can we do this.
I have solved the issue by my own and sharing here for others-
def save(self,commit=True):
        brand = super(BrandForm, self).save(commit=False)
        brand.image_url = self.image_url
        brand.save()
        return brand
Pages: 1 2