Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

321
Visualizações
Django model field to upload file from one app but save with another

We are developing an intranet with Django which has to have a consistent and centralized file managmenet. We implemented a filemanager app which should handle all the uploads and downloads, do mimetype checks, permission checks etc.

The upload ist achieved through a Django form:

class UploadFileForm(forms.ModelForm):
class Meta:
    model = PhysicalFile
    fields = ('path', 'directory')

def save(self, commit=True):
    """
    Override save method of ModelForm to create Physical File object of
    uploaded file and to process meta data
    """
    # Proceed with default behaviour but DO NOT commit!
    # pfile contains the PhysicalFile object which is not yet written to DB
    pfile = super(UploadFileForm, self).save(commit=False)

    # set pfile's meta data according to:
    # https://docs.djangoproject.com/en/1.11/ref/files/uploads/
    pfile.name = self.cleaned_data['path'].name
    pfile.size = self.cleaned_data['path'].size
    pfile.mimetype = self.cleaned_data['path'].content_type

    # NOW save to database, ignoring commit parameter
    pfile.save()

    return pfile

Now we need want to perform uploads in ANOTHER app (say a members app with profile picture upload) using the same form as above. However, it needs to be included into an app specific form. E.g. a form with name, address etc. Basically we would only need to save the corresponding foreignKey of the file into the memberModel and process the upload with the filemanger's form.

That is why we thought of a custom filed. But this is not working out at all..

class FilemanagerUploadField(models.ForeignKey):
def __init__(self, upload_to=None, *args, **kwargs):
    # Will be used later to bind specific apps to specific directories
    self.upload_to = upload_to
    # Bind PhysicalFile as default Model
    super(FilemanagerUploadField, self).__init__('filemanager.PhysicalFile')

def formfield(self, **kwargs):
    """ Taken from django's FileField but does NOT WORK"""
    defaults = {'form_class': forms.FileField, 'max_length': self.max_length} 

    if 'initial' in kwargs:
        defaults['required'] = False
    defaults.update(kwargs)
    return super(FilemanagerUploadField, self).formfield(**defaults)

def save(self):
    # somewho run form from here with uploaded data and return foreignKey

I am not really able to get a grip on those custom model fields... We need it to perform like a FileField (widget validation and stuff) but be saved like a ForeignKey (to the actual PhysicalFile Model in another app)...

If there is another way to achieve what we are looking for, please tell me.

tldr; Upload files in App A but let App B process it, save the file path, meta data etc, and return ForeignKey of the processed object to A to save it to database. Custom model field?

about 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda