I am trying to create a SlugField
in Django.
I created this simple model:
from django.db import models
class Test(models.Model):
q = models.CharField(max_length=30)
s = models.SlugField()
I then do this:
>>> from mysite.books.models import Test
>>> t=Test(q="aa a a a", s="b b b b")
>>> t.s
'b b b b'
>>> t.save()
>>> t.s
'b b b b'
I was expecting b-b-b-b
.
I'm using Django 1.7
Create a SlugField in your model like this:
Then in
admin.py
defineprepopulated_fields
;There is corner case with some utf-8 characters
Example:
This can be solved with Unidecode
You can look at the docs for the
SlugField
to get to know more about it in more descriptive way.A small correction to Thepeer's answer: To override
save()
function in model classes, better add arguments to it:Otherwise,
test.objects.create(q="blah blah blah")
will result in aforce_insert
error (unexpected argument).Use
prepopulated_fields
in your admin class:If you don't want to set the slugfield to Not be editable, then I believe you'll want to set the Null and Blank properties to False. Otherwise you'll get an error when trying to save in Admin.
So a modification to the above example would be::