imimali / coderun-2023-training

Live coding source from the Coderun 2023 training

Repository from Github https://github.comimimali/coderun-2023-trainingRepository from Github https://github.comimimali/coderun-2023-training

Django Dash - An introduction to Web Development for Speedsters

Introduction

Welcome to Django Dash! This is a workshop designed to introduce you to the world of web development using Django, a Python web framework. We will be building a simple web application.

Installation, creating a new project

I assume you already have Python installed. If you don't, you can download it from here.

Creating a virtual environment (optional, but recommended)

pip install virtualenv

Now create a virtual environment

python -m venv venv

Now activate the virtual environment

source venv/bin/activate

Or on windows

venv\Scripts\activate

This will isolate your installation so you don't have to worry about messing up your system installation.

Now let's Django

pip install Django

Easy enough, right? Now let's create a new project.

django-admin startproject coderun

πŸ’‘ startproject vs startapp

>> cd coderun
>> django-admin startproject demo

Explore the files and folders created by the command. You should see something like this:

coderun
β”œβ”€β”€ coderun
β”‚   β”œβ”€β”€ asgi.py
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ settings.py
β”‚   β”œβ”€β”€ urls.py
β”‚   └── wsgi.py
└── manage.py

Let's test if it worked:

>> python manage.py runserver

Let's create an app now:

>> python manage.py startapp demo

Now you should see something like this:

coderun
β”œβ”€β”€ coderun
β”‚   β”œβ”€β”€ asgi.py
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ settings.py
β”‚   β”œβ”€β”€ urls.py
β”‚   └── wsgi.py
β”œβ”€β”€ demo
β”‚   β”œβ”€β”€ admin.py
β”‚   β”œβ”€β”€ apps.py
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ migrations
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ models.py
β”‚   β”œβ”€β”€ tests.py
β”‚   └── views.py
└── manage.py

Creating a simple view

Let's create a simple view. Open demo/views.py and add the following code:

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world.")

Now we need to tell Django to use this view. Open demo/urls.py and add the following code:

from .views import index
from django.urls import path
 urlpatterns = [
    path('', index, name='index'),
]

Creating a simple template

Let's create a simple template. Create a new folder called templates in the demo folder. Create a new file called index.html in the templates folder and add the following code:

<div>
        {% if books %}

        {% for book in books%}
        <h1>Title: {{ book.title }}</h1>
        <h1>Author: {{ book.author }}</h1>
        {% endfor %}
        {% endif %}
    </div>

Now we need to tell Django to use this template. Open demo/views.py and add the following code:

from django.http import HttpResponse
from django.shortcuts import render
from .models import Book

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
        


def index(request):
    books = [
        Book('The Brothers Karamazov', 'Fyodor Dostoevsky'),
        Book('The Master and Margarita', 'Mikhail Bulgakov'),
    ]
    return render(request, 'index.html', {'books': books})

But hold on, we don't quite usually do it like this

Let's create a model. Open demo/models.py and add the following code:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

Now we need to tell Django to use this model. Open demo/admin.py and add the following code:

from django.contrib import admin
from .models import Book

admin.site.register(Book)

We didn't do this at the training but now you can do the following:

>> python manage.py makemigrations
>> python manage.py migrate

Now you can add books from the admin panel. You can go to localhost:8000/admin and login with the credentials you created when you ran python manage.py createsuperuser. If you didn't yet, do it and follow the instructions. It will help you create credentials to log in.

Creating a simple form

Let's create a simple form. Open demo/forms.py and add the following code:

from django import forms

class BookForm(forms.Form):
    title = forms.CharField(label='Title', max_length=100)
    author = forms.CharField(label='Author', max_length=100)

You can do this from actual html code, it's just a matter of preference. I personally find it easier to do it like this. You can take a look at the templates file in the code we wrote and see what kind of magic templating languages are capable of. Once you get the hang of the syntax, you can do some pretty cool stuff with it. Here's an explanation of what we've done there

<div>
    <div>
        <form method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Push me</button>
        </form>
    </div>
    <div>
        {% if books %}

        {% for book in books%}
        <h1>Title: {{ book.title }}</h1>
        <h1>Author: {{ book.author }}</h1>
        {% endfor %}
        {% endif %}
    </div>
</div>
  • The {% csrf_token %} part was necessary to avoid cross-site request forgery attacks. You can read more about it here.
  • The {{ form.as_p }} part took our form passed in the template context and rendered it as a paragraph. You can read more about it here.
  • The {% if books %} part is a conditional statement. You can read more about it here.
  • Analogously, you can do for loops and access the elements of the list. You can read more about it here. The actual html code will be rendered for each element of the list. You do need th e{% endfor %} part to close the loop, analogously for the if as well.

About

Live coding source from the Coderun 2023 training


Languages

Language:Python 96.1%Language:HTML 3.9%