Mateus Vahl
Mateus Vahl

Reputation: 989

django cutom image name on upload

I need create a image upload with django, the problem is, django always saving in a global project(called linkdump) folder, I want save it on the project folder(linktracker).

setting.py:

STATIC_URL = '/static/'

model:

class Link(models.Model):
    link_description = models.CharField(max_length=200)
    link_url = models.CharField(max_length=200)
    link_image = models.ImageField(upload_to= './static/')

    def __str__(self):
        return self.link_description

    class Admin:
        pass

now in the view:

<img src="{% static link.link_image %}" alt="{{ link.link_description }}">

it returns

http://127.0.0.1:8000/static/static/o-BLUE-LIGHT-SLEEP-facebook.jpg 

and the upload is in the project folder(linkdump), not inside the app.

Upvotes: 0

Views: 52

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

You can specify a function to return a custom path for the ImageField:

def get_upload_path(instance, filename):
    return 'your/custom/path/here'

class Link(models.Model):
    . . .
    link_image = models.ImageField(upload_to=get_upload_path)

Now you can use information from the model instance to build up the path to upload to.

Additionally, you don't want to use the {% static %} template tag to specify the path to the image. You would just use the .url property of the field:

<img src="{{ link.link_image.url }}" alt="{{ link.link_description }}" />

Upvotes: 1

Related Questions