Wednesday, January 26, 2011

Re: Customising the Admin Save Models in DJango 1.1


Hu,

On 26 Jan 2011, at 07:22, Prof Falken wrote:
I have two models, the first is a 'change request ticket' and the
second reflects the status of that ticket.  They are linked by a
ForeignKeyField on the first table.

You may find it best to collapse them into a single object; using the 'choice' option to allow the user to set the ticket's state.

The two problems that I have are:

1) Some of the 'states' should mark the ticket as closed, so when the
ticket is saved with the state of 'closed', it should be marked as
'completed' with the date and time the action was carried out.

You can jump in and change the model's data before the model is saved by over-riding the 'save' method in your model.

Below is one of my models.  My frequency attribute could be quite similar to what you need for your state field.  Below you can see where I'm setting a number of my attributes (based upon the parent object when the Charge object is created as an Inline) before this Charge is saved,

class Charge (models.Model):
    CHARGE_FREQUENCY_CHOICES = (
        (u'NRC', u'Non-Recurring'),
        (u'MRC', u'Monthly'),
        (u'QRC', u'Quaterly'),
        (u'ARC', u'Annual')
        )
    
    frequency = models.CharField(max_length=15, choices=CHARGE_FREQUENCY_CHOICES)
   <cut more attributes>
    
    def save(self, *args, **kwargs):
        self.description = self.service
        self.customer = self.service.customer
        self.legacy_charge_id = None
        self.prorata = False
        self.created_date = datetime.date.today()
        self.started_date = self.service.completed_date
        self.expiry_date = self.service.expiry_date
        self.terminated_date = self.service.terminated_date
        super(Charge, self).save(*args, **kwargs)

In order that the user does not set (or need to set) the above fields, set the fields attribute of the Admin object so only the values you want the user to control are visible.  Here's mine,

class ChargeInlineAdmin(admin.TabularInline):
    fields = ('frequency','amount', 'currency', 'vat_chargeable')
    model = Charge
    extra = 0


Regards,

aid

Adrian Bool



No comments:

Post a Comment