s.jawne.info.pl/prezentacja-django

Django

Django - framework

Framework webowy dla perfekcjonistów (z terminami)

Cechy:

Pojęcia

Typowy sposób działania

Plan ogólny

Prosta aplikacja do obsługi bloga, czyli:

Plan szczegółowy - widoki

Konieczne będą następujące widoki:

Plan szczegółowy - modele

Konieczne będą następujące modele:

Zaczynamy

Instalacja Django w środowisku Linux

$ cat blog/urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'blog.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
)

grep '^$' blog/setttings.py | head -n 25 | tail -n 25

"""
Django settings for blog project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd8=3avi1as%1k-n*b!p6#slp(7w6bn^bausv3e8g0_%a+utsyg'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',

$ grep -v '^$' blog/settings.py | head -n 50 | tail -n 25

'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'blog.urls'
WSGI_APPLICATION = 'blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'

$ grep '^$' blog/settings.py | head -n 75 | tail -n 25

USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'

Dodajemy naszą aplikacje "notes"

Edytujemy plik blog/settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'notes',
)

Migracje i serwer WWW

It works!

Hello world!

notes/views.py

from django.shortcuts import render

def hello(request):
        return render(request, 'notes/hello.html')

notes/templates/notes/hello.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hi!</title>
  </head>
  <body>Hello World!</body>
</html>

blogs/urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    url(r'^$', 'notes.views.hello'),
)

Wracamy do bloga

notes/models.py

from django.db import models
from django.conf import settings


class Category(models.Model):
    """A category of notes."""
    name = models.CharField(max_length=50)
    slug = models.SlugField()


class Note(models.Model):
    name = models.CharField("Title", max_length=200)
    categories = models.ManyToManyField('category')
    'text = models.TextField()
    done = models.BooleanField(default=True)

blog/urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
)

Migracje

Coś na początek

notes/admin.py

from django.contrib import admin
from .models import Note, Category

admin.site.register(Note)
admin.site.register(Category)

Panel administratora

Strona główna - wykaz aplikacji

Panel administratora

Strona główna - edycja obiektu

Panel administratora - demo

Autopodpowiadanie wielokrotnego wyboru

Różne rodzaje pól

notes/views.py

from django.shortcuts import render
from .models import Note, Category
def NoteList(request, category_slug=None):
    """A view of notes all or only selected category."""
    context = {}
    object_list = Note.objects
    if category_slug:
        object_list = object_list.filter(categories__slug=category_slug)
    object_list = object_list.all()
    context['object_list'] = object_list
    context['categories'] = Category.objects.all()
    return render(request, 'notes/note_list.html', context)

notes/templates/notes/base.html

<!DOCTYPE html>
<html lang="en">
 <head>
    <meta charset="utf-8">
    <title>{%block title%}Notki Gośki{%endblock%}</title>
  </head>
  <body>
    {%block sidebar%}{%endblock%}
    {%block content%}{%endblock%}
  </body>
</html>

notes/templates/notes/note_list.html

{%extends 'notes/base.html'%}

{%block sidebar%}
{%if categories%}
    <ul>
    {%for category in categories%}
    <li><a href="{% url 'notes.views.NoteList' category_slug=category.slug%}">{{category.name}}</a></li>
    {%endfor%}
    </ul>
{%else%}
    No categories.
{%endif%}
{%endblock%}

{%block content%}
{%for note in object_list%}
    <h2>{{note.name}}</h2>
{%endfor%}
{%endblock%}

blog/urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # url(r'^$', 'notes.views.hello'),
    url(r'^$', 'notes.views.NoteList'),
    url(r'^category-(?P<category-slug>\w+)$', 'notes.views.NoteList'),

    #url(r'^admin/', include(admin.site.urls)),
)

/