Začíname s Djangom

Úvod do web programovania s Django Frameworkom.

@RicCo386 / SPy o.z. / Github/ricco386

Creative Commons License

Čo to Django je?

Django je open source Python Web framework, ktorý využíva MVC (Model-View-Controllner) návrhový vzor.

Django zdôrazňuje DRY (dont repeat yourself) princíp, ale tiež prenositeľnosť komponentov, rýchly vývoj a znovupoužiteľnosť.

Oficialna stránka: https://djangoproject.com/

Inštalácia v Python 3.5

Vytvoríme a aktivujeme adresár envs3 pre lokálne závislosti

python3 -m venv envs3
(alternativne: pyvenv envs3)
source envs3/bin/activate
pip install django

Inštalácia v Python 2.7

Vytvoríme a aktivujeme adresár envs pre lokálne závislosti

virtualenv envs
source envs/bin/activate
pip install django

Pokiaľ nemáte pip alebo virtualenv nainštalované, balíky python-pip, python-virtualenv sa nachádzajú v štandardných repozitároch Fedora, Ubuntu.

Prvá Django app

django-admin.py startproject konferencia

python manage.py migrate

python manage.py runserver

python manage.py startapp mailinglist

vim konferencia/settings.py
Pridať novo vytvorenú aplikáciu medzi INSTALLED_APPS

Modely

vim mailinglist/models.py

from django.db import models

class Subscriber(models.Model):
    email = models.EmailField(max_length=255)
    subscribed_date = models.DateTimeField('Date subscribed', auto_now_add=True, blank=True)

    def __str__(self):  # __unicode__ on Python 2
        return self.email

class MailingList(models.Model):
    name = models.CharField(max_length=50)
    subscriber = models.ManyToManyField(Subscriber)

    def __str__(self):  # __unicode__ on Python 2
        return self.name

Migrácie

python manage.py makemigrations mailinglist

python manage.py migrate

RAW SQL: python manage.py sqlmigrate mailinglist 0001

Tvorba Admina

python manage.py createsuperuser

vim mailinglist/admin.py

from django.contrib import admin
from mailinglist.models import Subscriber, MailingList

admin.site.register(Subscriber)
admin.site.register(MailingList)

Modifikácia Admina

vim mailinglist/admin.py

from django.contrib import admin
from mailinglist.models import Subscriber, MailingList

class SubscriberAdmin(admin.ModelAdmin):
    list_display = ('email', 'subscribed_date')

admin.site.register(Subscriber, SubscriberAdmin)
admin.site.register(MailingList)

Prvé view

vim mailinglist/views.py

# -*- coding: utf-8 -*-
from django.http import HttpResponse

def index(request):
    return HttpResponse(u'Ahoj Svet.\
                        Práve ste v mailinglistovom indexe.')

Prvé URLs

vim mailinglist/urls.py

from django.conf.urls import url
from mailinglist import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

vim konferencia/urls.py

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

urlpatterns = [
    url(r'^ml/', include('mailinglist.urls')),
    url(r'^admin/', admin.site.urls),
]

Views čo aj niečo robia

vim mailinglist/views.py

# -*- coding: utf-8 -*-
from django.http import HttpResponse, Http404
from django.shortcuts import render
from mailinglist.models import MailingList

def mlist(request, list_id):
    try:
        ml = MailingList.objects.get(pk=list_id)
    except MailingList.DoesNotExist:
        raise Http404(u'Mailinglist neexistuje!!!')
    return render(request, 'mailinglist/mlist.html', {'ml': ml})

def subscribe(request, list_id):
    return HttpResponse(u'Práve sa zapisujete do mailinglistu: %s'
                        % list_id)

vim mailinglist/urls.py

from django.conf.urls import patterns, url
from mailinglist import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<list_id>\d+)/$', views.mlist, name='mlist'),
    url(r'^(?P<list_id>\d+)/subscribe/$', views.subscribe,
                                            name='subscribe'),
)

Prvý template

mkdir -p mailinglist/templates/mailinglist

vim mailinglist/templates/mailinglist/mlist.html

{{ ml.name }}

    {% for scb in ml.subscriber.all %}
  • {{ scb.email }} ({{ scb.subscribed_date }})
  • {% endfor %}

Prihlasovací Formulár

vim mailinglist/forms.py

# -*- coding: utf-8 -*-
from django.forms import ModelForm
from mailinglist.models import Subscriber

class SubscribeForm(ModelForm):
    class Meta:
        model = Subscriber
        fields = ('email',)

vim mailinglist/views.py

from django.shortcuts import render, get_object_or_404, redirect
from mailinglist.forms import SubscribeForm
from mailinglist.models import MailingList

def subscribe(request, list_id):
    ml = get_object_or_404(MailingList, pk=list_id)
    if request.method == "POST":
        form = SubscribeForm(request.POST)
        if form.is_valid():
            subscriber = form.save()
            ml.subscriber.add(subscriber)
            return redirect('mlist', list_id=list_id)
    else:
        form = SubscribeForm()
    return render(request, 'mailinglist/subscribe.html',
                  {'ml': ml, 'form': form})

vim mailinglist/templates/mailinglist/subscribe.html

{{ ml.name }}

{% csrf_token %} {{ form.as_p }}

Ďakujem za pozornosť

Creative Commons License
Začíname s Djangom vytvoril Richard Kellner prezentácia je licencovaná pod Creative Commons Attribution 4.0 International License.
Práca zverejnená na https://github.com/ricco386/zaciname-s-djangom.