Python Forum
How to save uploaded image url in database from Django?
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to save uploaded image url in database from Django?
#1
Hi All,

I have implemented a functionality-upload image to S3 from Django2.0.6+Python3.6+MySql.
And this functionality is working fine.
Now I want to save the uploaded image url to 'image_url' field of a table- Brand in database.
My image uploading code (models.py) is as below-
class Brand(models.Model):
    name = models.CharField(max_length=60)
    description = models.TextField(blank=True, null=True)
    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
def get_logo(logo_name, folder):
    logo_name_with_ext = '{}{}'.format(logo_name, '.png')
    logo_url = '{}/{}'.format(IMAGE_PATH, os.path.join(folder, logo_name_with_ext))
    return mark_safe('<img src="{}" height="20" />'.format(logo_url))
Can anyone please suggest me what changes should I make here?
Reply
#2
Please, post the part of your code where you use save() to write the new data to the DB.
You can do something like:

class Brand(models.Model):
    name = models.CharField(max_length=60)
    description = models.TextField(blank=True, null=True)
    image_url = models.TextField(blank=True, null=True)
    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
And make get_logo() returns 2 contents:

def get_logo(logo_name, folder):
    logo_name_with_ext = '{}{}'.format(logo_name, '.png')
    logo_url = '{}/{}'.format(IMAGE_PATH, os.path.join(folder, logo_name_with_ext))
    return mark_safe('<img src="{}" height="20" />'.format(logo_url)), logo_url
So, to write to the DB:

new_brand = Brand()
new_brand.name = "Brand Name"
new_brand.description = "Brand Description"
html_img_tag, new_brand.image_url = new_brand.logo()
new_brand.created_at = datetime.now() # Use your approach here
new_brand.updated_at = datetime.now() # Use your approach here
new_brand.save()
Reply
#3
(Jul-02-2018, 11:05 PM)gontajones Wrote: Please, post the part of your code where you use save() to write the new data to the DB.
You can do something like:

class Brand(models.Model):
    name = models.CharField(max_length=60)
    description = models.TextField(blank=True, null=True)
    image_url = models.TextField(blank=True, null=True)
    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
And make get_logo() returns 2 contents:

def get_logo(logo_name, folder):
    logo_name_with_ext = '{}{}'.format(logo_name, '.png')
    logo_url = '{}/{}'.format(IMAGE_PATH, os.path.join(folder, logo_name_with_ext))
    return mark_safe('<img src="{}" height="20" />'.format(logo_url)), logo_url
So, to write to the DB:

new_brand = Brand()
new_brand.name = "Brand Name"
new_brand.description = "Brand Description"
html_img_tag, new_brand.image_url = new_brand.logo()
new_brand.created_at = datetime.now() # Use your approach here
new_brand.updated_at = datetime.now() # Use your approach here
new_brand.save()

But it will add a new text field- image_url in the UI; and I don't want to display this field.
And for saving in DB I have not override anything, I am using default Django behaviour.
Reply
#4
Quote:I don't want to display this field

You can make image_url a hidden field.
image_url = forms.CharField(widget=forms.HiddenInput())
Or, in your template:
{{ form.image_url.as_hidden }}
Quote:I am using default Django behaviour.
Could you post your views.py, where you process the request.POST?
Reply
#5
(Jul-03-2018, 09:47 AM)gontajones Wrote:
Quote:I don't want to display this field

You can make image_url a hidden field.
image_url = forms.CharField(widget=forms.HiddenInput())
Or, in your template:
{{ form.image_url.as_hidden }}
Quote:I am using default Django behaviour.
Could you post your views.py, where you process the request.POST?

views.py is blank, I havenot made any changes here.
My changes are in models.py,admin.py and forms.py.
Reply
#6
Are you following a tutorial or something else to coding this way?

I recommend using the views.py when using Django.
Check this part of Django Forms documentations.
Reply
#7
(Jul-03-2018, 10:44 AM)gontajones Wrote: Are you following a tutorial or something else to coding this way?

I recommend using the views.py when using Django.
Check this part of Django Forms documentations.

I am following below official link and there is a concept of modelform that is I am using-
django modelform
Reply
#8
Try this:

class Brand(models.Model):

    name = models.CharField(max_length=60)
    description = models.TextField(blank=True, null=True)
    image_url = forms.CharField(widget=forms.HiddenInput())
    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()
Reply
#9
(Jul-04-2018, 09:53 AM)gontajones Wrote: Try this:

class Brand(models.Model):

    name = models.CharField(max_length=60)
    description = models.TextField(blank=True, null=True)
    image_url = forms.CharField(widget=forms.HiddenInput())
    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()

I am unable to understand the relationship between image_url and logo here-
new_brand = Brand()
new_brand.name = "Brand Name"
new_brand.description = "Brand Description"
html_img_tag = new_brand.logo('brand')
new_brand.save()
And if I add below line-
image_url = forms.CharField(widget=forms.HiddenInput())
It says
Error:
unresolved reference 'forms'
Once I change it to models, it says
Error:
AttributeError: module 'django.db.models' has no attribute 'HiddenInput'

For workaroung I movedd your changes in my forms.py as below-
class BrandForm(forms.ModelForm):
    logo = forms.ImageField(required=False)
    image_url = forms.CharField(widget=forms.HiddenInput())

    class Meta:
        model = Brand
        fields = '__all__'

    def clean_logo(self):
        valid_extensions = ['.png', '.jpg', '.jpeg']
        name = self.cleaned_data.get('name')
        logo = self.cleaned_data.get('logo')

        if logo:
            image_processor = ImageProcessor(logo)
            image_url = image_processor.upload(name, 'brand', valid_extensions)
            new_brand = Brand()
            new_brand.image_url = image_url
            new_brand.save()
        print('image_url is',image_url)
        return logo
But when I click on the save button, it says
Error:
Please correct the error below
Neither in server nor in log file there is any error.
Reply
#10
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Django: View is unable to find attributes of database model pythonpaul32 0 459 Dec-07-2023, 06:38 PM
Last Post: pythonpaul32
  Save JSON data to sqlite database on Django Quin 0 2,790 Mar-26-2022, 06:22 PM
Last Post: Quin
Question wkhtmltoimage generated jpeg save to Database using mongoengine Madoo 2 3,008 Aug-18-2020, 03:42 PM
Last Post: Madoo
  SHow image in a static link of Django pycada 3 2,486 Mar-04-2020, 01:50 AM
Last Post: pycada
  Send email to gmail after user fill up contact form and getting django database updat Man_from_India 0 2,059 Jan-22-2020, 03:59 PM
Last Post: Man_from_India
  how retrieve database save multiple data in web Django 2.1 taomihiranga 0 2,752 Jul-30-2019, 04:58 PM
Last Post: taomihiranga
  Django: How to automatically substitute a variable in the admin page at Django 1.11? m0ntecr1st0 3 3,217 Jun-30-2019, 12:21 AM
Last Post: scidam
  Read Save RadioButtons from Database in Python Flask Webpage Gary8877 0 7,086 Apr-11-2019, 12:33 AM
Last Post: Gary8877
  Django- Remove leading zeros in values from database ntuttle 1 3,441 Mar-07-2019, 07:30 PM
Last Post: nilamo
  how i save the html form to flask database mebaysan 1 7,227 Feb-07-2019, 12:56 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020