Daniel Garcia
Daniel Garcia

Reputation: 175

Default value for hidden field in Django model

I have this Model:

class Occurrence(models.Model):
    id = models.AutoField(primary_key=True, null=True)
    reference = models.IntegerField(null=True, editable=False)

    def save(self):
         self.reference = self.id
         super(Occurrence, self).save()

I want for the reference field to be hidden and at the same time have the same value as id. This code works if the editable=True but if I want to hide it it doesn't change the value of reference.

How can I fix that?

Upvotes: 0

Views: 2059

Answers (2)

rasca
rasca

Reputation: 354

there are a couple of things I'd like to comment about your code. First of all in save it should say reference and not collection, and the super should be indented inside save. You forgot to pass the arguments in super too. It should look like this:

class Occurrence(models.Model):
    id = models.AutoField(primary_key=True, null=True)
    reference = models.IntegerField(null=True, editable=False)

    def save(self):
        self.reference = self.id    
        super(Occurrence, self).save(*args, **kwargs)

This will work always despite the editable value. Editable is there just for the admin. By the way, I assume you are talking about hiding reference in the admin. As the id never changes once it's saved you can use it's value instead of the reference one.

Hope this helps.

Upvotes: 1

Steve Jalim
Steve Jalim

Reputation: 12195

Why not just use the id then? And you can expose it under the name 'reference' by making it a property, but it won't show up in any ModelForms, inlcuding the admin:

@property
def reference(self):
  try:
    return self.id
  except AttributeError: #in case the object is not yet saved
    return None

Upvotes: 2

Related Questions