Wednesday, January 25, 2017

Re: Extended user model to add Profile class want to slugify first_name last_name in profile class

On Wednesday 25 January 2017 07:43:50 David wrote:

> Thank you. That's very helpful. Now just need to work out how to make

> it a mandatory field in django admin, such that it is always created

> when a user is.

 

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

No comments:

Post a Comment