10π
You could override the models save-method so that when a new entity is created, you generate the slug on the fly. Something like:
if not self.pk:
self.slug = ''.join(random.sample(string.ascii_lowercase, 10))
You could do that, but it isnβt very good and better would be to let the slug be a deterministic slugified version of the objects name.
27π
You can use this when you want your slug to be generated automatically with the entry made in some other field in the same model, where the slug lies.
from django_extensions.db.fields import AutoSlugField
slug = AutoSlugField(_('slug'), max_length=50, unique=True, populate_from=('name',))
populate_from
is the field in the model which will auto generate the slug
5π
default
has to be a value or a callable.
So itβs default=some_method
, not default=some_method()
. Here is an example:
from django.contrib.auth.models import UserManager
def randomString():
um = UserManager()
return( um.make_random_password( length=25 ) )
class Foo( models.Model ):
code = models.CharField( max_length=25, default=randomString )
- How do you get Django to make a RESTful call?
- Django error admin.E033: username is not an attribute of users.CustomUser. Why is my custom user admin not working?
- Method in Django to display all attributes' values belonging to a created object?
- Whats the correct format for django dateTime?
1π
maybe model validation can help? http://docs.djangoproject.com/en/dev/ref/models/instances/
You can just simple validate the value which should be written in a slug field and if it exists already, generate something unique.
Also overriding of the models save method could be the solution.
Cheers.
- Django how to get count for manytomany field
- Hosting my Django site
- How do I set HttpOnly cookie in Django?
- How can I best find out how django works internally?
1π
searching in google, I found similar question: How to use slug in django
I think so the better approach is rewrite the save method, and validade the field in form.
But, slug should be unique, so generate random string is not good! Like Tommaso Bardugi say early, if you add the timestamp in url, this is resolved.
- Django template turn array into HTML table
- How can I move a field from one model to another, and still retain the data?
- Django reverse to contains/icontains
- Check if a function has a decorator