Django Bogotá. CBV

2,127 views
1,974 views

Published on

Django Meetup Bogotá. Class Based Views con ejemplos. Class Based Views with examples.
Código fuente: https://bitbucket.org/vero4ka/cbvexamples

Class Based Views with examles.

Published in: Technology, Business
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,127
On SlideShare
0
From Embeds
0
Number of Embeds
143
Actions
Shares
0
Downloads
40
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Django Bogotá. CBV

  1. 1. Class Based Views RosBusinessConsulting www.vero4ka.info @vero4ka_ru
  2. 2. Class Based Views Inspector http://ccbv.co.uk
  3. 3. CBV vs. FBV
  4. 4. Classes View TemplateView RedirectView ListView CreateView UpdateView DetailView DeleteView
  5. 5. from django.views.generic import View class MyViewClass(View): def get(self, request, *args, **kwargs): context = # calcular lo que usted desea pasar al template return self.render_to_response(context) def post(self, request, *args, **kwargs): context = # calcular lo que usted desea pasar al template return self.render_to_response(context) View class
  6. 6. Models
  7. 7. class Rubrica(models.Model): title = models.CharField(u'Título', max_length=255) def __unicode__(self): return unicode(self.title) class Noticia(models.Model): is_published = models.BooleanField(u'Status', default=False) pub_date = models.DateTimeField(u'Fecha de publicación', default=datetime.datetime.now) author = models.ForeignKey(User, verbose_name=u"Autor") rubric = models.ForeignKey(Rubrica, verbose_name=u"Rúbrica") title = models.CharField(u'Título', max_length=500, default=u'') body = models.TextField(u'Contenido') def __unicode__(self): return self.title class Meta(object): ordering = ['-pub_date'] Models
  8. 8. URLs
  9. 9. from django.conf.urls.defaults import patterns, url from django.views.generic import TemplateView from noticias import views urlpatterns = patterns("", # Index static page url(r'^$|^index/$', TemplateView.as_view(template_name='noticias/index.html'), name="index"), # List view url(r'^noticias/$', views.Noticias.as_view(), name="noticias"), # Update view url(r'^noticia/(?P<pk>d+)/$', views.UpdateNoticia.as_view(), name="update_noticia"), # Create view url(r'^noticia/create/$', views.CreateNoticia.as_view(), name="create_noticia"), # Detail view url(r'^noticia/(?P<pk>d+)/$', views.Noticia.as_view(), name="noticia"), # Delete view url(r'^noticia/delete/(?P<pk>d+)/$', views.DeleteNoticia.as_view(), name="delete_noticia"), ) URLs
  10. 10. Views
  11. 11. View: from django.views.generic import ListView from noticias.models import Noticia as NoticiasModel class Noticias(ListView): model = NoticiasModel template_name = "noticias/list.html" context_object_name = "noticias" Template: {% include "noticias/base.html" %} {% block main_content %} {% for noticia in noticias %} <p>{{ noticia.title }}</p> {% endfor %} {% endblock main_content %} ListView
  12. 12. class Noticias(ListView): model = NoticiasModel template_name = "noticias/list.html" context_object_name = "noticias" def get_context_data(self, **kwargs): context = super(Noticias, self).get_context_data(**kwargs) context.update(page_title='Lista de nuestras noticias') return context def get_queryset(self): return super(NoticiasDeCine, self).get_queryset().filter(rubric__slug="cine") ListView añadir data al contexto modificar queryset
  13. 13. View: class Noticias(ListView): model = NoticiasModel context_object_name = "noticias" paginate_by = 5 Template: {% for noticia in noticias %} <p>{{ noticia.title }}</p> {% endfor %} {% if paginator.num_pages > 1 %} {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}">Anterior</a> {% endif %} <span>Pagina {{ page_obj.number }} de {{ page_obj.paginator.num_pages }}</span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">Siguiente</a> {% endif %} {% endif %} ListView paginación
  14. 14. View: from django.views.generic import DetailView class Noticia(DetailView): model = NoticiasModel template_name = "noticias/detail.html" context_object_name = "noticia" Template: <p>{{ noticia.pub_date }}</p> <p>{{ noticia.title }}</p> <p>{{ noticia.rubric }}</p> <p>{{ noticia.author }}</p> <p>{{ noticia.body }}</p> URLs: url(r'^noticia/(?P<pk>d+)/$', views.Noticia.as_view(), name="noticia"), DetailView buscar un objeto por pk
  15. 15. View: from django.views.generic import DetailView class Pubrica(DetailView): model = RubricaModel template_name = "noticias/rubrica.html" slug_field = "slug" Template: <p> <b>Title:</b> {{ object.title }} </p> <p> <b>Slug:</b> {{ object.slug }} </p> URLs: url(r'^rubrica/(?P<slug>w+)/$', views.Pubrica.as_view(), name="rubrica"), DetailView buscar un objeto por slug
  16. 16. Form Views
  17. 17. Form: from django import forms class ContactenosForm(forms.Form): email = forms.EmailField(label="Email") name = forms.CharField(label="Nombre") message = forms.CharField(label="Mensaje", widget=forms.Textarea()) View: class Contactenos(FormView): form_class = ContactenosForm template_name = "noticias/contactenos.html" success_url = reverse_lazy("gracias") URLs: url(r'^contactenos/$', views.Contactenos.as_view(), name="contactenos"), url(r'^gracias/$', TemplateView.as_view(template_name='noticias/gracias.html'), name="gracias"), FormView
  18. 18. Template: {% include "noticias/base.html" %} {% block main_content %} <div class="container"> <form method="post" action="">{% csrf_token %} <div class="row"> <div class="span12">{{ form }}</div> </div> <div class="row"> <div class="span12"> <button type="submit" class="btn btn-success">Save</button> </div> </div> </form> </div> {% endblock main_content %} FormView
  19. 19. from django.shortcuts import redirect class Contactenos(FormView): form_class = ContactenosForm template_name = "noticias/contactenos.html" success_url = reverse_lazy("gracias") def form_valid(self, form): send_mail('Email de {0}'.format(form.cleaned_data["name"]), form.cleaned_data["message"], form.cleaned_data["email"] ['example@'example.com], fail_silently=False) return redirect(self.get_success_url()) FormView enviar un correo cuando el formulario es correcto
  20. 20. Otros metodos: def form_invalid(self, form): """ Acciones a realizar si el formulario es incorrecto. """ return self.render_to_response(self.get_context_data(form=form)) def get_initial(self): """ Definir un diccionario que será utilizado para proveer los datos iniciales del formulario """ return self.initial.copy() FormView
  21. 21. Form: from django.forms import ModelForm from noticias.models import Noticia class NoticiaForm(ModelForm): class Meta(): model = Noticia exclude = ('pub_date',) View: from django.views.generic import CreateView class CreateNoticia(CreateView): model = NoticiasModel template_name = "noticias/form.html" form_class = NoticiaForm success_url = reverse_lazy("noticias") CreateView
  22. 22. View: from django.views.generic import UpdateView class UpdateNoticia(UpdateView): model = NoticiasModel template_name = "noticias/form.html" form_class = NoticiaForm success_url = reverse_lazy("noticias") URLs: url(r'^noticia/update/(?P<pk>d+)/$', views.UpdateNoticia.as_view(), name="update_noticia"), UpdateView
  23. 23. View: from django.views.generic import DeleteView class DeleteNoticia(DeleteView): model = NoticiasModel success_url = reverse_lazy("noticias") template_name = "noticias/delete_confirm.html" Template: <div class="container"> <form method="post" action="">{% csrf_token %} <div class="row"> <div class="span3"><a href="{% url noticias %}" class="btn btn-danger" >Cancel</a></div> <div class="span3"> <button type="submit" class="btn btn-success">Yes, I'm sure</button> </div> </div> </form> </div> DeleteView
  24. 24. Do one thing, and do it well The UNIX philosophy
  25. 25. Mixin
  26. 26. import json from django.http import HttpResponse class JSONResponseMixin(object): response_class = HttpResponse def render_to_response(self, context, **response_kwargs): response_kwargs['content_type'] = 'application/json' return self.response_class( self.convert_context_to_json(context), **response_kwargs ) def convert_context_to_json(self, context): return json.dumps(context) class NoticiasJSON(JSONResponseMixin, ListView): model = NoticiasModel Mixin
  27. 27. Decoradores
  28. 28. ● En URLs: from django.contrib.auth.decorators import login_required as _lr urlpatterns = patterns("", url(r'^noticias/$', _lr(views.Noticias.as_view()), name="noticias"), ) ● En Views: from django.contrib.auth.decorators import login_required from django.views.utils.decorators import method_decorator class Niticias(ListView): @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(Niticias, self).dispatch(*args, **kwargs) Decoradores
  29. 29. Gracias por su atención! Ejemplos: https://bitbucket.org/vero4ka/cbvexamples

×