-1

I have this model in Django:

    dms_dok_titel = models.CharField(max_length=255, blank=True)
    dms_dok_beschreibung = models.CharField(max_length=3000, blank=True, null=True)
    dms_dok_datei = models.FileField(max_length=255,upload_to='DMS/')
    dms_dok_hochgeladen_am = models.DateField()
    dms_dok_indiziert = models.BooleanField(default=False)
    dms_dok_gehoert_zu_app = models.CharField(max_length=255, choices=app_choices, blank=False, null=False)
    dms_dok_typ = models.CharField(max_length=255, choices=typ_choices, blank=False, null=False, default='Sonstiges')

    def save(self, *args, **kwargs):
        preserve_ext = extension(self.dms_dok_datei.name)
        neuer_dateiname = self.dms_dok_gehoert_zu_app + '_' + self.dms_dok_titel + '_' + self.dms_dok_hochgeladen_am.strftime("%d.%m.%Y")
        self.dms_dok_datei.name = neuer_dateiname + preserve_ext
        super(DMS_Dokument, self).save(*args, **kwargs)

    def delete(self):
        self.indexes.all().delete()
        super(DMS_Dokument, self).delete()

    class Meta:
        app_label = 'DMS'

At another place in my code I do something with the objects from this class and I want to update just one field (dms_dok_indiziert).

So I thought I could just set this object's value (tmp_obj) to true and then do tmp_obj.save(). But for whatever reason, it always messes up my file's name in the database. The usual upload script generates something like 'DMS/nameofthefile.pdf', but after saving tmp_obj it just becomes 'nameofthefile.pdf'.

I tried this:

tmp_obj.dms_dok_datei.name = 'foo'
#tmp_obj.dms_dok_datei.name = 'DMS/' + tmp_obj.dms_dok_datei.name
print(tmp_obj.dms_dok_datei.name)
tmp_obj.save()

And yes, it prints 'foo'. Still, when I save the object, then in the database it is again 'nameofthefile.pdf'.

I just don't get it. :(

MDoe
  • 163
  • 1
  • 13
  • Where are you calling the save from? As in what function is this inside? Is it a class method? – mattyx17 Jul 15 '20 at 14:06
  • Dear mattyx17, thanks for your reply. I hope I am not celebrating to early, but I think I solved this with a tmp_obj.save(update_field=...) command. :) – MDoe Jul 15 '20 at 15:22

1 Answers1

1

I have seen a response here, please check it out. This might help:

tmp_obj.dms_dok_datei.name = "name_you_want"
tmp_obj.dms_dok_datei.field.upload_to = 'DMS/'
tmp_obj.save()
Jeffrey
  • 184
  • 1
  • 1
  • 9
  • 1
    Thank you, as mentioned in the other comment, I might have solved it with the update_fields (not field) parameter. But if I am celebrating too early, I will try your approach :). – MDoe Jul 15 '20 at 15:23