On Wednesday 25 January 2017 03:50:12 David wrote:
> I have extended Django's default user model to add a Profile model;
> bio etc.
>
> I want to slugify the users first_name last_name in profile class, so
> I can search for all X entities written by a specific user in the url
> form:
>
> /blog/authors/bob-smith
Strike the idea to give admin control over the slug. Instead, use django-autoslug and make the field not editable. Let autoslug handle conflicts by using sane values for populate_from and unique_with.
Example (from the docs):
# autoslugify value from a custom callable
# (ex. usage: user profile models)
slug = AutoSlugField(populate_from=lambda instance: instance.user.get_full_name())
Which is basically what you try to accomplish in the admin.
--
Melvyn Sopacua
That can be done:
These profile models are not special in any way - they are just Django models that happen to have a one-to-one link with a user model. As such, they aren’t auto created when a user is created, but a django.db.models.signals.post_save could be used to create or update related models as appropriate.
Here's a mixin I use (lots of models have a unique 'name' attribute in this project) which also defines a handy permalink. As you can see, the field is not even editable (so won't show in the admin), yet for each saved model a slug is generated as the field is required (blank is not set and defaults to false).
class SlugMixin(models.Model):
slug = AutoSlugField(
populate_from='name', unique=True, editable=False,
)
_detail_view_name = None
@models.permalink
def get_absolute_url(self):
model_name = self._meta.object_name.lower()
viewname = self._detail_view_name or '{}_detail'.format(model_name)
return viewname, [str(self.slug)]
absolute_url = property(get_absolute_url, doc="Permalink")
class Meta:
abstract = True
--
Melvyn Sopacua