Django: How to create Content Types and Permissions for already created tables

Background

Instances of ContentType have methods for returning the model classes they represent and for querying objects from those models. ContentType also has a custom manager that adds methods for working with ContentType and for obtaining instances of ContentType for a particular model.

ContentTypes, apart from a lot of awesomeness to build genericness in your Django app (as quoted), is also essential for defining Permissions in Django admin interface (remember this widget from the User and Groups models in Django admin?)

I recently worked on a project in which I had to setup an admin interface on top of already existing tables. For some reason (because someone had played around with it earlier), the django_content_type and auth_permission tables also existed.

Creating Models from existing tables

The first step was to create relevant models using the inspectdb management command.

python manage.py inspectdb

Creating ContentTypes and Permissions

Now, since the models were already synced, I had to fake the migrations, which would not create content_type or auth_permission entries. So, I used the following snippet to create the same.

Easy peesy!