[Django]-Django: Auto Generate a CharField using data from another CharField

6👍

Override your model’s save() method and set the url field value there:

class MyModel(models.Model):
    name = models.CharField(max_length=140)
    url = models.CharField(max_length=140)

    def save(self, *args, **kwargs):
        self.url = self.name.replace(' ', '_').lower()
        super(MyModel, self).save(*args, **kwargs)

See also:

Also note that, having a field that is just a logical transformation of another field of the model is basically a sign that you are doing things incorrectly. Consider having a property or a custom method (get_url(), for example) on a model instead.

👤alecxe

2👍

1) You could either turn url into a @property of your Model:

name = models.CharField(max_length=140)

@property
def url(self):
    return self.name.replace(" ", "_").lower()

2) Or override the the model’s save method:

name = models.CharField(max_length=140)
url = models.CharField(max_length=140)

def save(self, *args, **kwargs):
    self.url = self.name.replace(" ", "_").lower()
    super(ModelName, self).save(*args, **kwargs)

The difference between the two is that in 1 the url is not saved to the database, while in 2 it is. Implement whichever fits your situation better.

1👍

If you are using django admin, you could just slugify it.

In your model you would have:

name = models.CharField(max_length=140)
slug = models.CharField()

Then in admin.py:

class YourModelAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("name",)}

admin.site.register(YourModel, YourModelAdmin)

see https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields for more

👤Renkai

Leave a comment