SlideShare una empresa de Scribd logo
1 de 41
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
Hjörtur Hilmarsson
 
Resource and view
Resource and viewResource and view
Resource and view
Papp Laszlo
 

La actualidad más candente (20)

Jsf
JsfJsf
Jsf
 
Get AngularJS Started!
Get AngularJS Started!Get AngularJS Started!
Get AngularJS Started!
 
Django Vs Rails
Django Vs RailsDjango Vs Rails
Django Vs Rails
 
Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
The Rails Way
The Rails WayThe Rails Way
The Rails Way
 
Polymer
PolymerPolymer
Polymer
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UI
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
Vue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówVue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentów
 
Creating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web ComponentsCreating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web Components
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" Domino
 
Java Web Development with Stripes
Java Web Development with StripesJava Web Development with Stripes
Java Web Development with Stripes
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Stripes Framework
Stripes FrameworkStripes Framework
Stripes Framework
 
Gutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisablesGutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisables
 
ActiveResource & REST
ActiveResource & RESTActiveResource & REST
ActiveResource & REST
 
Resource and view
Resource and viewResource and view
Resource and view
 
CRUD with Dojo
CRUD with DojoCRUD with Dojo
CRUD with Dojo
 
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAXМихаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
 
Creating GUI container components in Angular and Web Components
Creating GUI container components in Angular and Web ComponentsCreating GUI container components in Angular and Web Components
Creating GUI container components in Angular and Web Components
 

Destacado

Bourne supremacy
Bourne supremacyBourne supremacy
Bourne supremacy
kavanagh123
 
Maiadia Company Profile In Brief V03
Maiadia Company Profile In Brief V03Maiadia Company Profile In Brief V03
Maiadia Company Profile In Brief V03
MAIADIA
 
Questionnaire Presentation
Questionnaire PresentationQuestionnaire Presentation
Questionnaire Presentation
abisola-oke
 
Questionnaire Results
Questionnaire ResultsQuestionnaire Results
Questionnaire Results
abisola-oke
 
Media question 2
Media question 2Media question 2
Media question 2
abisola-oke
 
Contoh Daftar riwayat hidup Akhyadi
Contoh Daftar riwayat hidup AkhyadiContoh Daftar riwayat hidup Akhyadi
Contoh Daftar riwayat hidup Akhyadi
Aditiga Serang
 

Destacado (19)

Bourne supremacy
Bourne supremacyBourne supremacy
Bourne supremacy
 
Maiadia Company Profile In Brief V03
Maiadia Company Profile In Brief V03Maiadia Company Profile In Brief V03
Maiadia Company Profile In Brief V03
 
Powsys may2008
Powsys may2008Powsys may2008
Powsys may2008
 
Questionnaire Presentation
Questionnaire PresentationQuestionnaire Presentation
Questionnaire Presentation
 
Public final
Public finalPublic final
Public final
 
Ieee Meeting Anacapri
Ieee Meeting AnacapriIeee Meeting Anacapri
Ieee Meeting Anacapri
 
Questionnaire Results
Questionnaire ResultsQuestionnaire Results
Questionnaire Results
 
Distribution
DistributionDistribution
Distribution
 
Media question 2
Media question 2Media question 2
Media question 2
 
Pos daya
Pos dayaPos daya
Pos daya
 
The agar wood industry yet to utilize in bangladesh
The agar wood industry yet to utilize in bangladeshThe agar wood industry yet to utilize in bangladesh
The agar wood industry yet to utilize in bangladesh
 
Burton's theory
Burton's theoryBurton's theory
Burton's theory
 
An Analysis of SAFTA in the Context of Bangladesh
An Analysis of SAFTA in the Context of BangladeshAn Analysis of SAFTA in the Context of Bangladesh
An Analysis of SAFTA in the Context of Bangladesh
 
The Bangladeshi Agarwood Industry: Development Barriers and a Potential Way...
The Bangladeshi Agarwood Industry:   Development Barriers and a Potential Way...The Bangladeshi Agarwood Industry:   Development Barriers and a Potential Way...
The Bangladeshi Agarwood Industry: Development Barriers and a Potential Way...
 
Javascript by geetanjali
Javascript by geetanjaliJavascript by geetanjali
Javascript by geetanjali
 
Ecommerce final
Ecommerce finalEcommerce final
Ecommerce final
 
How to critique articles
How to critique articlesHow to critique articles
How to critique articles
 
Contoh Daftar riwayat hidup Akhyadi
Contoh Daftar riwayat hidup AkhyadiContoh Daftar riwayat hidup Akhyadi
Contoh Daftar riwayat hidup Akhyadi
 
Primary versus Secondary Sources for Evidence-Based Medicine
Primary versus Secondary Sources for Evidence-Based MedicinePrimary versus Secondary Sources for Evidence-Based Medicine
Primary versus Secondary Sources for Evidence-Based Medicine
 

Similar a Django Bogotá. CBV

Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
Luka Zakrajšek
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
Ganga Ram
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
Fabien Potencier
 
Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)
Reinout van Rees
 
Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)
Leonardo Soto
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
Leonardo Soto
 

Similar a Django Bogotá. CBV (20)

Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Django
DjangoDjango
Django
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Django Girls Mbale [victor's sessions]
Django Girls Mbale [victor's sessions]Django Girls Mbale [victor's sessions]
Django Girls Mbale [victor's sessions]
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, Tricks
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)
 
Web Components With Rails
Web Components With RailsWeb Components With Rails
Web Components With Rails
 
Vue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue routerVue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue router
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
 

Último

Último (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 

Django Bogotá. CBV

  • 2.
  • 3. Class Based Views Inspector http://ccbv.co.uk
  • 6. 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
  • 8. 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
  • 10. 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
  • 11. Views
  • 12. 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
  • 13.
  • 14. 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
  • 15.
  • 16. 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
  • 17.
  • 18. 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
  • 19.
  • 20. 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
  • 21.
  • 23. 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
  • 24. 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
  • 25.
  • 26. 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
  • 27.
  • 28. 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
  • 29. 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
  • 30.
  • 31. 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
  • 32.
  • 33. 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
  • 34.
  • 35. Do one thing, and do it well The UNIX philosophy
  • 36. Mixin
  • 37. 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
  • 38.
  • 40. ● 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
  • 41. Gracias por su atención! Ejemplos: https://bitbucket.org/vero4ka/cbvexamples