SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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 UIOliver Häger
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
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ówLaravel Poland MeetUp
 
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 ComponentsRachael L Moore
 
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" DominoRob Bontekoe
 
Java Web Development with Stripes
Java Web Development with StripesJava Web Development with Stripes
Java Web Development with StripesSamuel Santos
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
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éutilisablesRiad Benguella
 
ActiveResource & REST
ActiveResource & RESTActiveResource & REST
ActiveResource & RESTRobbert
 
Resource and view
Resource and viewResource and view
Resource and viewPapp Laszlo
 
Михаил Крайнюк - 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 AJAXDrupalSib
 
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 ComponentsRachael L Moore
 

Was ist angesagt? (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
 

Andere mochten auch

Bourne supremacy
Bourne supremacyBourne supremacy
Bourne supremacykavanagh123
 
Maiadia Company Profile In Brief V03
Maiadia Company Profile In Brief V03Maiadia Company Profile In Brief V03
Maiadia Company Profile In Brief V03MAIADIA
 
Questionnaire Presentation
Questionnaire PresentationQuestionnaire Presentation
Questionnaire Presentationabisola-oke
 
Ieee Meeting Anacapri
Ieee Meeting AnacapriIeee Meeting Anacapri
Ieee Meeting Anacapripasq_tlc
 
Questionnaire Results
Questionnaire ResultsQuestionnaire Results
Questionnaire Resultsabisola-oke
 
Media question 2
Media question 2Media question 2
Media question 2abisola-oke
 
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 bangladeshMd. Joynal Abdin
 
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 BangladeshMd. Joynal Abdin
 
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...Md. Joynal Abdin
 
Contoh Daftar riwayat hidup Akhyadi
Contoh Daftar riwayat hidup AkhyadiContoh Daftar riwayat hidup Akhyadi
Contoh Daftar riwayat hidup AkhyadiAditiga Serang
 

Andere mochten auch (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
 

Ähnlich wie 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
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction DjangoWade Austin
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Django Girls Mbale [victor's sessions]
Django Girls Mbale [victor's sessions]Django Girls Mbale [victor's sessions]
Django Girls Mbale [victor's sessions]Victor Miclovich
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"GeeksLab Odessa
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
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
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksShawn Rider
 
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
 
Web Components With Rails
Web Components With RailsWeb Components With Rails
Web Components With RailsBoris Nadion
 
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 routerKaty Slemon
 
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
 

Ähnlich wie 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)
 

Kürzlich hochgeladen

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Kürzlich hochgeladen (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

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