Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 979
TheMeaningfulEngineer Avatar asked Sep 28 '13 21:09

TheMeaningfulEngineer


2 Answers

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

like image 179
Manikandan Sigamani Avatar answered Oct 20 '22 16:10

Manikandan Sigamani


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.

like image 43
MrKsn Avatar answered Oct 20 '22 15:10

MrKsn