Django model conditional default value based on other field

There is two tables Company and Template_message

each company can have desired template messages for each message

messages have 3 types ( invitation,rejection,Job_offer)

now i want to set a default text for each template_message which the company can change it later on

but i dont know how to set the default value for each template message , based on their type

the model i designed is bellow :

class TemplateMessage(models.Model):
        ('1', 'invitation'),
        ('2', 'Rejecting'),
        ('3', 'Job_offer_acceptance'),

    type = models.CharField(max_length=4, choices=TEMPLATE_TYPE_CHOICES, default='1')

    def subject_initials(type):
        match type:
            case 1:
                return "[jobName] skills test invitation from [companyName]"
            case 2:
                return "Thank you  from [companyName]"
            case 3:
                return "Job offer letter from [companyName]"

    subject = models.CharField(max_length=256, default=subject_initials(type))
    company = models.ForeignKey('Company', on_delete=models.CASCADE)

    class Meta:
        unique_together = ("company", "type")

    def __str__(self):
        return self.type

but it does not not work and when i go to admin panel the subject text is not set to any default value

you should override ModelAdmin.get_changeform_initial_data method for your ModelAdmin.

class MyModelAdmin(ModelAdmin):

    ... # any staff before

    def get_changeform_initial_data(self, request):
        initial_data = super().get_changeform_initial_data(request)
        initial_data['subject'] = subject_initials(get_type_from(request))
        return initial_data

    ... # any staff after

Other possibility_ override ModelAdmin.changeform, to add in request.GET['subject'] = your_initial_subject.

class MyModelAdmin(ModelAdmin):
    ... # any staff before

    def changeform_view(self, request, *args, **kwargs):
        request.GET._mutable = True
        request.GET['subject'] = your_initial_subject
        return super().changeform_view(request, *args, **kwargs)

    ... # any staff after

But changing the request.GET/POST internal is a bad paractice.

Back to Top