I have two charfields, name
and url
. name
is something like "My group", and I want the url
field to be automatically derived from the name
entry. So it would be something like "my_group".
This is how I tried to accomplish this, but it doesn't work.
name = models.CharField(max_length=140)
url = models.CharField(max_length=140, default=name.replace (" ", "_"))
Any ideas?
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.
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.