Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Start on Django

Start on Django

Tarsis Azevedo

November 08, 2013
Tweet

More Decks by Tarsis Azevedo

Other Decks in Programming

Transcript

  1. Quem sou eu?! • Programador globo.com • Entusiasta python e

    django • #cobrateam • tarsisazevedo.com Thursday, November 14, 13
  2. E voces? • Trabalham com web? • Com algum framework?

    • E front-end? Thursday, November 14, 13
  3. Por que Django? • Framework para perfeccionistas com prazo •

    O facil é facil • O complexo é possivel • Documentação imensa e boa Thursday, November 14, 13
  4. E o que nao tem! • Testes =/ • Organização

    de projetos grandes • Modularização de JS Thursday, November 14, 13
  5. Bora começar! • mkvirtualenv start-on-django • pip install django south

    • django-admin.py startproject to_do . • chmod +x manage.py Thursday, November 14, 13
  6. settings.py # Django settings for to_do project. import os PROJECT_ROOT

    = os.path.abspath(os.path.dirname(__file__)) Thursday, November 14, 13
  7. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'to_do.db',

    'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } Thursday, November 14, 13
  8. Django Admin! • Facil de usar • Facil de extender

    • Completo Thursday, November 14, 13
  9. urls.py from django.conf.urls import patterns, include, url from django.contrib import

    admin admin.autodiscover() urlpatterns = patterns( '', # Examples: # url(r'^$', 'to_do.views.home', name='home'), # url(r'^to_do/', include('to_do.foo.urls')), url(r'^admin/', include(admin.site.urls)), ) Thursday, November 14, 13
  10. tasks/views.py from django.views.generic import ListView from tasks.models import Task class

    TaskList(ListView): template_name = 'tasks.html' model = Task Thursday, November 14, 13
  11. urls.py from django.conf.urls import patterns, include, url from django.contrib import

    admin from tasks.views import TaskList admin.autodiscover() urlpatterns = patterns( '', url(r'^$', TaskList.as_view(), name='index'), # url(r'^to_do/', include('to_do.foo.urls')), url(r'^admin/', include(admin.site.urls)), ) Thursday, November 14, 13
  12. HTML <html> <head> <meta charset="utf-8"> <title>My Tasks!</title> <link rel="stylesheet" href="{{

    STATIC_URL }}css/tasks.css" type="text/css" media="screen" /> </head> <body> <div class="grid-12"> <h1 class='titulo'>My Tasks!</h1> <ul class="tasks"> {% for task in object_list %} <li class="task">{{ task.descricao }}</li> {% endfor %} </ul> </div> </body> </html> Thursday, November 14, 13
  13. CSS .grid-12 { width: 1055px; margin: 0 auto; } .titulo

    { font-family: Helvetica; font-size: 45px; } Thursday, November 14, 13
  14. CSS .tasks { font-family: Arial; font-size: 18px; width: 500px; }

    .tasks .task { border-bottom: 1px solid #dcdcdc; height: 30px; margin-bottom: 5px; line-height: 30px; } Thursday, November 14, 13
  15. urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns

    = patterns( ... ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Thursday, November 14, 13
  16. HTML <form action="/tasks/create/" method="post" accept-charset="utf-8"> {% csrf_token %} {{ form.as_ul

    }} <input class="salvar-task"type="submit" value="Continue &rarr;"/> </form> Thursday, November 14, 13
  17. Ajax!!! <script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript"></script> <script type="text/javascript" language="javascript" charset="utf-8"> $(document).ready(function(){ $(".adicionar-tarefa").click(function(){

    $.ajax({ url: '/tasks/create/', method: 'GET', success: function(data) { $('.tasks').append('<li class="task"></li>'); $('.task:last-child').append(data); } }); return false; }); }); </script> Thursday, November 14, 13
  18. CSS .adicionar-tarefa { border: 1px solid black; color: black; display:

    inline-block; height: 20px; padding: 5px; margin-top: 20px; } .adicionar-tarefa:hover { color: blue; } Thursday, November 14, 13
  19. Mais JS $(document).on('click', '.salvar-task', function() { var task = $(this).closest('.task');

    var form = $(this).closest('form'); var data_processada = $(form).serialize(); var request = $.ajax({ url: $(form).attr('action'), method: 'POST', data: data_processada }); request.done(function(data) { $(task).html(data); }); return false; }); Thursday, November 14, 13
  20. tasks/views.py from django.views.generic import CreateView, DetailView class TaskCreate(CreateView): model =

    Task class TaskDetail(DetailView): model = Task Thursday, November 14, 13
  21. tasks/models.py from django.db import models class Task(models.Model): descricao = models.CharField(max_length=255)

    def get_absolute_url(self): return "/task/%s/" % self.id Thursday, November 14, 13
  22. tasks/models.py from django.db import models class Task(models.Model): ... done =

    models.BooleanField(default=False) ... Thursday, November 14, 13
  23. task.html <li class="task {% if task.done %}done{% endif %}"> {%

    csrf_token %} <input data-update-url='{{ task.get_absolute_url }}update/' type="checkbox" name="done" {% if task.done %}checked{% endif %}/> {{ task.descricao }} </li> Thursday, November 14, 13
  24. tasks.html ... <ul class="tasks"> {% for task in object_list %}

    {% include "tasks/task.html" %} {% endfor %} </ul> ... Thursday, November 14, 13
  25. JS $(document).on('click', '.task input[name="done"]', function() { var task = $(this).parent();

    var data_processada = $(this).parent().find('input').serialize(); var task_update_url = $(this).data('update-url'); $.ajax({ url: task_update_url, type: 'POST', data: data_processada, success: function(data) { $(task).toggleClass('done'); }, }); $(this).attr('checked', true); }); Thursday, November 14, 13
  26. tasks/views.py from django import forms from django.views.generic import ListView, CreateView,

    DetailView, UpdateView ... class TaskUpdateForm(forms.ModelForm): class Meta: model = Task fields = ['done'] class TaskUpdate(UpdateView): model = Task form_class = TaskUpdateForm Thursday, November 14, 13
  27. E o adicionar?! ... class TaskCreateForm(forms.ModelForm): class Meta: model =

    Task fields = ['descricao'] class TaskCreate(CreateView): model = Task form_class = TaskCreateForm ... Thursday, November 14, 13
  28. E o HTML de add? <form action="/tasks/create/" method="post" accept-charset="utf-8"> {%

    csrf_token %} {{ form.descricao }} <input class="salvar-task" type="submit" value="Continue &rarr;"/> </form> Thursday, November 14, 13
  29. tasks/forms.py from django import forms from tasks.models import Task class

    TaskCreateForm(forms.ModelForm): class Meta: model = Task fields = ['descricao'] class TaskUpdateForm(forms.ModelForm): class Meta: model = Task fields = ['done'] Thursday, November 14, 13
  30. tasks/views.py from django.views.generic import ListView, CreateView, DetailView, UpdateView from tasks.forms

    import TaskCreateForm, TaskUpdateForm from tasks.models import Task class TaskList(ListView): template_name = 'tasks.html' model = Task class TaskCreate(CreateView): model = Task form_class = TaskCreateForm class TaskDetail(DetailView): model = Task class TaskUpdate(UpdateView): model = Task form_class = TaskUpdateForm Thursday, November 14, 13
  31. tasks/static/js/tasks.js $(document).ready(function(){ $(".adicionar-tarefa").click(function(){ $.ajax({ url: '/tasks/create/', method: 'GET', success: function(data)

    { $('.tasks').append('<li class="task"></li>'); $('.task:last-child').append(data); } }); return false; }); $(document).on('click', '.salvar-task', function() { var task = $(this).closest('.task'); var form = $(this).closest('form'); var data_processada = $(form).serialize(); var request = $.ajax({ url: $(form).attr('action'), method: 'POST', data: data_processada }); request.done(function(data) { $(task).replaceWith(data); }); return false; }); Thursday, November 14, 13
  32. tasks/static/js/tasks.js $(document).on('click', '.task input[name="done"]', function() { var task = $(this).parent();

    var data_processada = $(this).parent().find('input').serialize(); var task_update_url = $(this).data('update-url'); $.ajax({ url: task_update_url, type: 'POST', data: data_processada, success: function(data) { $(task).toggleClass('done'); }, }); $(this).attr('checked', true); }); }); Thursday, November 14, 13
  33. tasks.html <html> <head> <meta charset="utf-8"> <title>My Tasks!</title> <link rel="stylesheet" href="{{

    STATIC_URL }}css/tasks.css" type="text/css" media="screen" charset="utf-8"/> </head> <body> <div class="grid-12"> <h1 class='titulo'>My Tasks!</h1> <ul class="tasks"> {% for task in object_list %} {% include "tasks/task.html" %} {% endfor %} </ul> <a class="adicionar-tarefa" href="/tasks/create/">Adicionar tarefa</a> </div> <script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript" charset="utf-8"></script> <script src="{{ STATIC_URL }}js/tasks.js" type="text/javascript" charset="utf-8"></script> </body> </html> Thursday, November 14, 13
  34. task.html <li class="task {% if task.done %}done{% endif %}"> {%

    csrf_token %} <input data-update-url='{{ task.get_absolute_url }}update/' type="checkbox" name="done" {% if task.done %}checked{% endif %}/> {{ task.descricao }} <a class='delete' href='{{ task.get_absolute_url }} delete/'>x</a> </li> Thursday, November 14, 13
  35. JS $(document).on('click', '.task .delete', function() { var task = $(this).parent();

    var task_delete_url = $(this).attr('href'); var request = $.ajax({ url: task_delete_url, type: 'POST', }); request.done(function(data) { $(task).destroy(); }); return false; }); Thursday, November 14, 13
  36. urls.py ... from tasks.views import TaskList, TaskCreate, TaskDetail, TaskUpdate, TaskDelete

    url(r'^task/(?P<pk>\w+)/delete/$', TaskDelete.as_view(), name='delete_task'), ... Thursday, November 14, 13
  37. CSS .task .delete { display: inline-block; width: 10px; background: #ddd;

    font-size: 15px; text-align: center; padding: 0 10px; color: #bbb; text-decoration: none; float: right; } .task .delete:hover { background: #eee; color: black; } Thursday, November 14, 13
  38. tasks/models.py from django.db import models class Categoria(models.Model): nome = models.CharField(max_length=255)

    class Task(models.Model): descricao = models.CharField(max_length=255) done = models.BooleanField(default=False) categoria = models.ForeignKey(Categoria, blank=True, null=True) def get_absolute_url(self): return "/task/%s/" % self.id Thursday, November 14, 13
  39. tasks/forms.py ... class TaskCreateForm(forms.ModelForm): class Meta: model = Task fields

    = ['descricao', 'categoria'] ... Thursday, November 14, 13
  40. task_form.html <form action="/tasks/create/" method="post" accept-charset="utf-8"> {% csrf_token %} {{ form.descricao

    }} {{ form.categoria }} <input class="salvar-task" type="submit" value="Continue &rarr;"/> </form> Thursday, November 14, 13
  41. task.html ... {{ task.descricao }} {% if task.categoria %} -

    <span class="categoria">{{ task.categoria }}</span>{% endif %} ... Thursday, November 14, 13
  42. CSS ... .task .categoria { background-color: #ddd; border-radius: 4px; color:

    #333; display: inline-block; font-size: 15px; height: 15px; line-height: 15px; padding: 3px; } ... Thursday, November 14, 13
  43. E a exibição das categorias?? ... class Categoria(models.Model): nome =

    models.CharField(max_length=255) def __unicode__(self): return self.nome ... Thursday, November 14, 13
  44. Ao infinito... • funcionalidades do django • queryset api •

    herança de template • apps instalaveis Thursday, November 14, 13
  45. E alem! • powerful admin • temas para admin •

    github • heroku Thursday, November 14, 13