Django Bogotá. CBV
Upcoming SlideShare
Loading in...5
×
 

Django Bogotá. CBV

on

  • 1,660 views

Django Meetup Bogotá. Class Based Views con ejemplos. Class Based Views with examples.

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.

Statistics

Views

Total Views
1,660
Views on SlideShare
1,585
Embed Views
75

Actions

Likes
1
Downloads
27
Comments
0

2 Embeds 75

http://cansadadeserfeliz.wordpress.com 72
https://cansadadeserfeliz.wordpress.com 3

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Django Bogotá. CBV Django Bogotá. CBV Presentation Transcript

  • Class Based Views RosBusinessConsulting www.vero4ka.info @vero4ka_ru
  • Class Based Views Inspector http://ccbv.co.uk
  • CBV vs. FBV
  • Classes View TemplateView RedirectView ListView CreateView UpdateView DetailView DeleteView
  • 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
  • Models
  • 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
  • URLs
  • 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
  • Views
  • 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
  • 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
  • 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
  • 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
  • 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
  • Form Views
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • Do one thing, and do it well The UNIX philosophy
  • Mixin
  • 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
  • Decoradores
  • ● 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
  • Gracias por su atención! Ejemplos: https://bitbucket.org/vero4ka/cbvexamples