Tutorial: Using django-sb-codefield
This tutorial will guide you step-by-step through setting up and using django-sb-codefield in a new Django project, just like our demoproject.
Prerequisites¶
Python 3.11+
uv (or pip)
Django 4.2+
1. Create a Django Project¶
First, create a new directory for your project and set up a virtual environment.
mkdir myproject && cd myproject
uv venv
source .venv/bin/activateInstall Django and django-sb-codefield:
uv pip install django django-sb-codefieldInitialize your Django project and create an app:
django-admin startproject myproject .
python manage.py startapp myapp2. Update Settings¶
In myproject/settings.py, you need to add both codemirror2 and django_sb_codefield to your INSTALLED_APPS. Also, add your new app myapp.
INSTALLED_APPS = [
# ... your other installed apps
"django.contrib.staticfiles",
"codemirror2",
"django_sb_codefield",
"myapp",
]3. Create a Model with CodeField¶
Open myapp/models.py and create a model using the CodeField provided by the package. This field stores code snippets and renders a CodeMirror editor.
from django.db import models
from django_sb_codefield.fields import CodeField
class SampleCodeModel(models.Model):
name = models.CharField(max_length=200)
# Add the CodeField
code = CodeField(
modes=["javascript"],
options={
"mode": "javascript",
"theme": "monokai",
},
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name4. Register the Model in Django Admin¶
To ensure the CodeMirror editor renders correctly in the Django Admin interface, you must use the CodeFieldAdminMixin when registering your model.
Open myapp/admin.py:
from django.contrib import admin
from django_sb_codefield.admin import CodeFieldAdminMixin
from .models import SampleCodeModel
@admin.register(SampleCodeModel)
class SampleCodeModelAdmin(CodeFieldAdminMixin, admin.ModelAdmin):
list_display = ("name", "created_at", "updated_at")5. Run Migrations and Start the Server¶
Now apply the migrations to create your database tables and create a superuser to access the admin site.
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuserFinally, start the development server:
python manage.py runserverNavigate to http://127.0.0.1:8000/admin/ in your browser, log in, and try creating a new SampleCodeModel. You will see a beautiful CodeMirror editor where you can type JavaScript code!