{"id":23070488,"url":"https://github.com/lucrae/django-cheat-sheet","last_synced_at":"2025-04-03T10:19:05.671Z","repository":{"id":38360920,"uuid":"138101686","full_name":"lucrae/django-cheat-sheet","owner":"lucrae","description":"A cheat sheet for creating web apps with the Django framework.","archived":false,"fork":false,"pushed_at":"2022-10-20T18:24:05.000Z","size":28,"stargazers_count":791,"open_issues_count":4,"forks_count":245,"subscribers_count":32,"default_branch":"master","last_synced_at":"2025-02-08T23:41:17.439Z","etag":null,"topics":["django"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lucrae.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-06-21T00:56:16.000Z","updated_at":"2025-02-08T18:56:41.000Z","dependencies_parsed_at":"2023-01-19T16:03:41.894Z","dependency_job_id":null,"html_url":"https://github.com/lucrae/django-cheat-sheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucrae%2Fdjango-cheat-sheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucrae%2Fdjango-cheat-sheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucrae%2Fdjango-cheat-sheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucrae%2Fdjango-cheat-sheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lucrae","download_url":"https://codeload.github.com/lucrae/django-cheat-sheet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246981165,"owners_count":20863828,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django"],"created_at":"2024-12-16T06:26:56.149Z","updated_at":"2025-04-03T10:19:05.617Z","avatar_url":"https://github.com/lucrae.png","language":null,"funding_links":[],"categories":["Back-End Development"],"sub_categories":[],"readme":"# :scroll: Django Cheat Sheet\nA cheat-sheet for creating web apps with the Django framework using the Python language. Most of the summaries and examples are based on [the official documentation](https://docs.djangoproject.com/en/2.0/) for Django v2.0.\n\n## Sections\n- :snake: [Initializing pipenv](#snake-initializing-pipenv-optional) (optional)\n- :blue_book: [Creating a project](#blue_book-creating-a-project)\n- :page_with_curl: [Creating an app](#page_with_curl-creating-an-app)\n- :tv: [Creating a view](#tv-creating-a-view)\n- :art: [Creating a template](#art-creating-a-template)\n- :ticket: [Creating a model](#ticket-creating-a-model)\n- :postbox: [Creating model objects and queries](#postbox-creating-model-objects-and-queries)\n- :man: [Using the Admin page](#man-using-the-admin-page)\n\n\n## :snake: Initializing pipenv (optional)\n- Make main folder with `$ mkdir \u003cfolder\u003e` and navigate to it with `$ cd \u003cfolder\u003e`\n- Initialize pipenv with `$ pipenv install`\n- Enter pipenv shell with `$ pipenv shell`\n- Install django with `$ pipenv install django`\n- Install other package dependencies with `$ pipenv install \u003cpackage_name\u003e`\n\n## :blue_book: Creating a project\n- Navigate to main folder with `$ cd \u003cfolder\u003e`\n- Create project with `$ django-admin startproject \u003cproject_name\u003e`\n\nThe project directory should look like this:\n```\nproject/\n    manage.py\n    project/\n        __init__.py\n        settings.py\n        urls.py\n        wsgi.py\n```\n- Run the development server with `$ python manage.py runserver` within the project directory\n- If you want your `SECRET_KEY` to be more secure, you can set it to reference an environment variable\n- In the `settings.py` file within the project directory change the `SECRET_KEY` line to the following:\n```python\nSECRET_KEY = os.environ.get('SECRET_KEY')\n```\n- To quickly generate a random hex for your secret key:\n```python\n\u003e\u003e\u003e import secrets\n\u003e\u003e\u003e secrets.token_hex()\n```\n- You can set this environment variable in your shell with `export SECRET_KEY=\u003csecret_key\u003e`\n\n## :page_with_curl: Creating an app\n- Navigate to the outer project folder  `$ cd \u003couter_project_folder\u003e`\n- Create app with  `$ python manage.py startapp \u003capp_name\u003e`\n- Inside the `app` folder, create a file called `urls.py`\n\nThe project directory should now look like this:\n```\nproject/\n    manage.py\n    db.sqlite3\n    project/\n        __init__.py\n        settings.py\n        urls.py\n        wsgi.py\n    app/\n        migrations/\n            __init__.py\n        __init__.py\n        admin.py\n        apps.py\n        models.py\n        tests.py\n        urls.py\n        views.py\n```\n- To include this app in your project, add your app to the project's `settings.py` file by adding its name to the `INSTALLED_APPS` list:\n```python\nINSTALLED_APPS = [\n\t'app',\n\t# ...\n]\n```\n- To migrate changes over:\n```bash\n$ python manage.py migrate\n```\n\n## :tv: Creating a view\n- Within the app directory, open `views.py` and add the following:\n```python\nfrom django.http import HttpResponse\n\ndef index(request):\n    return HttpResponse(\"Hello, World!\")\n```\n- Still within the app directory, open (or create)  `urls.py` \n```python\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n    path('', views.index, name='index'),\n]\n```\n- Now within the project directory, edit `urls.py` to include the following\n```python\nfrom django.contrib import admin\nfrom django.urls import include, path\n\nurlpatterns = [\n    path('app/', include('app.urls')),\n    path('admin/', admin.site.urls),\n]\n```\n- To create a url pattern to the index of the site, use the following urlpattern:\n```python\nurlpatterns = [\n    path(\"\", include('app.urls')),\n]\n```\n- Remember: there are multiple files named `urls.py`\n- The `urls.py` file within app directories are organized by the `urls.py` found in the project folder.\n\n## :art: Creating a template\n- Within the app directory, HTML, CSS, and JavaScript files are located within the following locations:\n```\napp/\n   templates/\n      index.html\n   static/\n      style.css\n      script.js\n```\n- To add a template to views, open `views.py` within the app directory and include the following:\n```python\nfrom django.shortcuts import render\n\ndef index(request):\n    return render(request,'index.html')\n```\n- To include context to the template:\n```python\ndef index(request):\n\tcontext = {\"context_variable\": context_variable}\n    return render(request,'index.html', context)\n```\n- Within the HTML file, you can reference static files by adding the following:\n```html\n{% load static %}\n\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\t\u003chead\u003e\n\t\t\u003cmeta charset=\"UTF-8\"\u003e\n\t\t\u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1\"\u003e\n\t\t\n\t\t\u003clink rel=\"stylesheet\" href=\"{% static 'styles.css' %}\"\u003e\n\t\u003c/head\u003e\n\u003c/html\u003e\n```\n- To make sure to include the following in your `settings.py`:\n```python\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = [\n\tos.path.join(BASE_DIR, \"static\")\n]\n```\n- To add an `extends`:\n```html\n{% extends 'base.html'%}\n\n{% block content %}\n\nHello, World!\n\n{% endblock %}\n```\n- And then in `base.html` add:\n```html\n\u003cbody\u003e\n\t{% block content %}{% endblock %}\n\u003c/body\u003e\n```\n\n## :ticket: Creating a model\n- Within the app's `models.py` file, an example of a simple model can be added with the following:\n```python\nfrom django.db import models\n\nclass Person(models.Model):\n\tfirst_name = models.CharField(max_length=30)\n\tlast_name = models.CharField(max_length=30)\n```\n*Note that you don't need to create a primary key, Django automatically adds an IntegerField.*\n\n- To perform changes in your models, use the following commands in your shell:\n```\n$ python manage.py makemigrations \u003capp_name\u003e\n$ python manage.py migrate\n```\n*Note: including \u003capp_name\u003e is optional.*\n- A one-to-many relationship can be made with a `ForeignKey`:\n```python\nclass Musician(models.Model):\n    first_name = models.CharField(max_length=50)\n    last_name = models.CharField(max_length=50)\n    instrument = models.CharField(max_length=100)\n\nclass Album(models.Model):\n    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)\n    name = models.CharField(max_length=100)\n    release_date = models.DateField()\n    num_stars = models.IntegerField()\n```\n- In this example, to query for the set of albums of a musician:\n```python\n\u003e\u003e\u003e m = Musician.objects.get(pk=1)\n\u003e\u003e\u003e a = m.album_set.get()\n```\n \n- A many-to-many relationship can be made with a `ManyToManyField`:\n```python\nclass Topping(models.Model):\n    # ...\n    pass\n\nclass Pizza(models.Model):\n    # ...\n    toppings = models.ManyToManyField(Topping)\n```\n*Note that the `ManyToManyField`  is **only defined in one model**. It doesn't matter which model has the field, but if in doubt, it should be in the model that will be interacted with in a form.*\n\n- Although Django provides a `OneToOneField` relation, a one-to-one relationship can also be defined by adding the kwarg of `unique = True` to a model's `ForeignKey`:\n```python\nForeignKey(SomeModel, unique=True)\n```\n\t\n- For more detail, the [official documentation for database models]( https://docs.djangoproject.com/en/2.0/topics/db/models/) provides a lot of useful information and examples.\n\n## :postbox: Creating model objects and queries\n- Example `models.py` file:\n```python\nfrom django.db import models\n\nclass Blog(models.Model):\n    name = models.CharField(max_length=100)\n    tagline = models.TextField()\n\n    def __str__(self):\n        return self.name\n\nclass Author(models.Model):\n    name = models.CharField(max_length=200)\n    email = models.EmailField()\n\n    def __str__(self):\n        return self.name\n\nclass Entry(models.Model):\n    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)\n    headline = models.CharField(max_length=255)\n    body_text = models.TextField()\n    pub_date = models.DateField()\n    mod_date = models.DateField()\n    authors = models.ManyToManyField(Author)\n    n_comments = models.IntegerField()\n    n_pingbacks = models.IntegerField()\n    rating = models.IntegerField()\n\n    def __str__(self):\n        return self.headline\n```\n- To create an object within the shell:\n```\n$ python manage.py shell\n```\n```python\n\u003e\u003e\u003e from blog.models import Blog\n\u003e\u003e\u003e b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')\n\u003e\u003e\u003e b.save()\n```\n- To save a change in an object:\n```python\n\u003e\u003e\u003e b.name = 'The Best Beatles Blog'\n\u003e\u003e\u003e b.save()\n```\n- To retrieve objects:\n```python\n\u003e\u003e\u003e all_entries = Entry.objects.all()\n\u003e\u003e\u003e indexed_entry = Entry.objects.get(pk=1)\n\u003e\u003e\u003e find_entry = Entry.objects.filter(name='Beatles Blog')\n```\n\n## :man: Using the Admin page\n- To create a `superuser`:\n```bash\n$ python manage.py createsuperuser\n```\n- To add a model to the Admin page include the following in `admin.py`:\n```python\nfrom django.contrib import admin\nfrom .models import Author, Book\n\nadmin.site.register(Author)\nadmin.site.register(Book)\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flucrae%2Fdjango-cheat-sheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flucrae%2Fdjango-cheat-sheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flucrae%2Fdjango-cheat-sheet/lists"}