Django Cheatsheet

Field notes from learning Django

Source: RealPython

Background

Cheatsheet & Snippets

python3 -m venv <name>
source venv/bin/activate
pip install django
django-admin startproject <name> .
django-admin startapp <name>
python3 manage.py runserver
python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py createsuperuser
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='characters')
pip install djangorestframework
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
class Authors(APIView):
renderer_classes = [JSONRenderer]

# return all the unique authors of books
def get(self, request):
authors = Books.objects.order_by().values('author').distinct()
return Response(states)
from django.urls import path, include
from rest_framework import routers
from .views import BookViewSet, Authors

router = routers.DefaultRouter()
# ModelViewSet
router.register('books', BookViewSet)
urlpatterns = [
path('', include(router.urls))
# APIView
path('authors/', Authors.as_view(), name="authors")
]
from dj_database_url import parse as dburl

# this replaces the initial default for the local db
default_dburl = 'postgres://localhost/<dbname>'

DATABASES = {
'default': config('DATABASE_URL', default=default_dburl, cast=dburl),
}
from dj_static import Cling from django.core.wsgi import get_wsgi_application  os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<project>.settings")  application = Cling(get_wsgi_application())
-r requirements-dev.txt 
gunicorn
psycopg2
web: gunicorn <project>.wsgi --log-file -
python3 manage.py runscript <script.py>

Example workflow to build a REST API with Django

urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include('api.urls')),
]

Further Reading

--

--

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