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.
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.
- [Django]-Best practices: Good idea to create a new table for every user?
- [Django]-Error on django runserver – OverflowError: getsockaddrarg: port must be 0-65535
- [Django]-Keep User and Group in same section in Django admin panel
- [Django]-How to translate labels and validation messages of forms within Django
- [Django]-How to edit default django home page and new page
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
- [Django]-Django.core.exceptions.ImproperlyConfigured: Cannot import 'category'. Check that 'api.category.apps.CategoryConfig.name' is correct
- [Django]-Populate CheckboxSelectMultiple with existing data from django model form
- [Django]-Django, queryset to return manytomany of self
- [Django]-Django-extensions test_error_logging
- [Django]-Django – button url