TheMeaningfulEngineer
TheMeaningfulEngineer

Reputation: 16349

Get application name in Django model

The following is the model for a Django app. Let the app be called MyApp. The idea is for every app to have it's folder under the MEDIA_ROOT.

class MyModel(models.Model):
    .... #Other fields
    datoteka = models.FileField(upload_to = 'MyApp',null = True)

Is there a way to get the name of the app from somewhere and remove the hardcoded MyApp.

This is a similar question, however I have no access to the request object in the model.

Upvotes: 11

Views: 11281

Answers (2)

MrKsn
MrKsn

Reputation: 1207

from os import path

def _get_upload_to(instance, filename):
    return path.join(instance._meta.app_label, 'subdir', filename)

class MyModel(models.Model):
    ....
    datoteka = models.FileField(upload_to=_get_upload_to, ...)

Will result in 'MyApp/subdir' upload path.

Upvotes: 3

Manikandan Sigamani
Manikandan Sigamani

Reputation: 1984

There is an attribute app_label in _meta attribute. Please see this stackoverflow question

Upvotes: 15

Related Questions