Search code examples
pythondjangomakemigrations

Django makemigrations Issue


I am stumped. I have a custom model field class that looks for two arguments: app_name and file_dir.

In my model definition I have this:

files = MultiFileUploadAndViewer(app_name = getAppName(), file_dir='RequestedFiles', blank=True)

getAppName() is:

#appconfig imported from apps.py 
def getAppName():
    return <appConfig>.name

And the custom field definition is:

class MultiFileUploadAndViewer(models.FilePathField):

def __init__(self, *args, **kwargs):
    print(kwargs['app_name'])
    self.app_name = kwargs.pop('app_name')
    self.file_dir = kwargs.pop('file_dir','') + '\\'
    self.path = MEDIA_ROOT + '\\' + self.app_name + '\\' + self.file_dir
    self.upload_url = reverse(self.app_name +':File Upload') + '\\' + self.file_dir
    kwargs.update({'path':self.path})
    super(MultiFileUploadAndViewer, self).__init__(*args, **kwargs)

I deleted everything in the migrations folder except for init.py.

Upon running makemigrations, it throws a KeyError complaining that 'app_name' is not in kwargs.

However, notice the call to print() in the fields init method. That successfully prints the app_name. The KeyError comes after. Is the init function being called twice or something? Thus throwing the error after 'app_name gets popped off of kwargs? How can I address this issue? If I provide a default for app_name in the pop() method, this works, but I want it to error out if app_name (or file_dir) are not present in kwargs.


Solution

  • The init method is called again by the super class models.FilePathField here:

    super(MultiFileUploadAndViewer, self).__init__(*args, **kwargs)
    

    And you are deleting the kwargs app_name here

    self.app_name = kwargs.pop('app_name')