Extend Django User Model

Django CMS has its own User model but you might need to add attributes and other properties to it (like an avatar, right ?). The easiest way to do that is to extend that model with another model (we’ll call it UserProfile) and link them together using a one-to-one relationship.

Creating the UserProfile model

Nothing special here, I’m sure you know how it works.

Creating a UserProfile when creating a User

Each User needs to have a UserProfile object. To make sure that applies to every user, we’ll create a UserProfile each time a User is created. To do that. we’ll use the post_save signal (signals doc).

Just under the UserProfile code, you can add that code

And you’re pretty much good to go. You can access the user’s UserProfile using user.user_profile.

Find Application Support Directory in Swift (OSX, iOS)

It’s quite easy actually, once you know the answer…

 

Django REST Framework : add an attribute on the fly in a Serializer

Seralizers from DRF are doing a very good job at converting any Model to JSON data. They are even more awesome when you know how to add custom attributes to them.

In my case, I needed to add an attribute based on the current logged in user and related data from my model. To do that, I used a SerializerMethodField.

From the doc :

This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.

And the example :

Here’s a preview of how I implemented it :

Basically, this sets a field to True or False if the current user is ‘liking’ the Post object.

This is a pretty neat feature that I don’t want to forget about, so that’s why I’m writing it down here.