开发者

Django prepopulation + appending fixed string

开发者 https://www.devze.com 2023-03-26 00:47 出处:网络
Consider the following (simplified) Django model: Noun(models.Model): noun = models.CharField(max_length=30)

Consider the following (simplified) Django model:

Noun(models.Model):
    noun = models.CharField(max_length=30)
    plural = models.CharField(max_length=30)

I want to be abl开发者_开发技巧e to enter, say, 'cat' in the noun field and have the plural field be automatically populated with 'cats'. That is, I want to define a string to be appended to the end of a prepopulated field. Is this possible?

I know I can prepopulate it with 'cat' with the appropriate setting in admin.py, but this is not enough. Of course, it is also important that I be able to edit the entry after prepopulation (in case of irregular words). Any ideas would be much appreciated.


Make the plural blank=True and do something like this in your save():

def save(self, *args, **kwargs):
    if not self.plural:
        self.plural = self.noun + 's'
    super(Noun, self).save(*args, **kwargs)

I would actually do this in javascript client side so the data entry person can correct if it is incorrect.

0

精彩评论

暂无评论...
验证码 换一张
取 消