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

Gaurav Toshniwal
Mar 4, 2018 · 1 min read

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!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store