user1545895
user1545895

Reputation: 1821

django set default value of a model field to a self attribute

I have a model called Fattura, and I would like to set the default value of the field "printable" to a string that includes the value of the field "numero".

But I have the error that link_fattura has less arguments, but if I add default=link_fattura(self) I have an error because self is not defined.

How can I solve this issue?

class Fattura(models.Model):
        def link_fattura(self, *args, **kwargs):
                return u"http://127.0.0.1:8000/fatture/%s/" % (self.numero)
        data = models.DateField()
        numero = models.CharField("Numero", max_length=3)
        fatturaProForma = models.ForeignKey(FatturaProForma)
        printable = models.CharField("Fattura stampabile", max_length=200, default=link_fattura)
        def __unicode__(self):
                return u"%s %s" % (self.data, self.numero)
        class Meta:
                verbose_name_plural = "Fatture"
                ordering = ['data']

Upvotes: 1

Views: 2744

Answers (2)

Hedde van der Heide
Hedde van der Heide

Reputation: 22459

Sorry I read you question wrong, that's not possible without javascript because your model hasn't been saved at that stage yet.

You could forecast the url by doing something like:

def link_facttura(self):
    if not self.id:
        return some_url/fattura/%d/ % Fattura.objects.latest().id+1
    return u""

But it's ugly and likely to cause erros once you start deleting records

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600041

You can't do this using the default argument. The best bet is to override the save method:

def save(self, *args, **kwargs):
    if not self.id and not self.printable:
        self.printable = self.link_fattura()
    return super(Fattura, self).save(*args, **kwargs)

Upvotes: 2

Related Questions