Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django class based views (VII) - Epíleg
El món de les class based views dóna per molt, la possibilitat de sobreescriure funcions, canviar paràmetres i anar combinant mixins fins a obtenir el que necessitam ens permet reutilitzar molt de codi i de manera elegant. En aquest darrer post de la sèrie veurem algunes de les situacions més habituals en les que ens podem trobar i la facilitat amb que es resolen. El formulari per defecte no és el que vull Sovint quan editam un objecte mitjançant un formulari ens trobam que hi ha camps que no volem que s'editin. A l'exemple que hem fet servir fins ara imaginem que no volem que una vegada s'ha crear l'slug es pugui modificar. Per fer això el que hem de fer és crear un formulari nou. Com que es bo tenir les coses organitzades ho farem dins el fitxer forms.py class SampleEditForm(forms.ModelForm): class Meta: model = Sample exclude = ('slug',) i llavors a la classe que implementa l'edició li direm que agafi aquest formulari per a editar l'objecte from forms import SampleEditForm class SampleUpdateView(UpdateView): model = Sample success_url = reverse_lazy('tutorial_list_sample') form_class=SampleEditForm Volem poder filtrar/ordenar els resultats El ListView és un component idial per a fer cerques i filtres. Amb una … -
Django class based views (VI) - Lists
En aquesta sisena entrega (que hi ha algú per aquí ho ja us heu dormit tots?) veurem com podem mostrar llistes d'objectes que sovint podem trobar amb els CRUD. Per a mostrar llistats (paginats o no) Django ens proporciona la classe ListView que es pot trobar a dango.views.generic.list. Aquesta classe és hereva de MultipleObjectTemplateResponseMixin i de BaseListView. BaseListView és el que la la feina, ja que és fill de MultipleObjectMixin i de View implementant-ne el mètode get. Com les vistes orientades als CRUD també en aquest cas tenim una plantilla per defecte, formada pel nom del model i el sufixe '_list'. El que més ens interessa són doncs els mètodes i atributs de MultipleObjectMixin. Primer de tot, però anem a fer-ho fàcil, mostrarem la llista dels objectes que hem creat al post anterior: A l'url: url(r'^tutorial/sample/list/$', SampleListView.as_view(), name='tutorial_list_sample'), i al views.py podem fer from django.views.generic.list import ListView class SampleListView(ListView): model = Sample i ara haurem de definir la plantilla que tindrà com a nom sample_list.html, primer, però és convenient conèixer quines variables es passen al context, a saber: paginator page_obj is_paginated object_list Els valors poden canviar en funció de si tenim paginació o no, però les variables que tenim són … -
Django class based views (V) - CRUD
Creant un CRUD En aquesta cinquena part veurem com podem crear tot el relacionat amb un manteniment, el famós CRUD (Create, Retreive, Update, Delete). La part de Retreive ja l'hem vista a l'article anterior, però hi tornarem per a que ens quedi un exemple complet. Partirem del següent model: class Sample(models.Model): """this is just a sample model""" slug = models.SlugField(max_length=50, unique=True) name = models.CharField(max_length=100) ammount = models.IntegerField() comments = models.TextField(blank=True, null=True) class Meta: verbose_name = 'Sample' verbose_name_plural = 'Sample' def __unicode__(self): return self.name Django a més de DetailView ens proporciona les següents vistes ja construïdes per fer aquest tipus de tasques: * `CreateView` que gestiona la creació * `UpdateView` que gestiona l'actualització * `DeleteView` gestiona l'esborrat Comencem! Creació Definim primer la url url(r'^tutorial/sample/create/$', SampleCreateView.as_view(), name='tutorial_create_sample'), Hem anomenat a la nostra classe SampleCreateView així que la definirem al views.py from django.views.generic.edit import CreateView from main.models import Sample class SampleCreateView(CreateView): model = Sample Amb això Django ja ens crearà internament un formulari i l'intentarà presentar a una plantilla que es construeix amb el nom del model i el sufixe _form, és a dir, en el nostre cas sample_form.html passant com a variable de context el formulari creat form Si volem fer via … -
Dummies doing dummy things
It can often be interesting to test hypothetical situations. So the other day I did a little stress test to see how Evennia handles many players. This is a follow-up to the open bottlenecks post.Evennia, being based on Twisted, is an asynchronous mud server. This means that the program is not multi-threaded but instead it tries to divide up the code it runs into smaller parts. It then quickly switches between executing these parts in turn, giving the impression of doing many things at the same time. There is nothing magical about this - each little piece of code blocks the queue as it runs. So if a particular part takes too long, everyone else will have to wait for their turn. Likewise, if Twisted cannot flip through the queue as fast or faster than new things get added to it, it will start to fall behind. The good thing is that all code in the queue will run, although if the event loop cannot keep up there will be a noticeable delay before it does. In a mud, this results in "lagging" (in addition to whatever lag is introduced by your network connection). Running Evennia with a handful of … -
My PyCon 2012 Schedule
Here I was thinking that this year's PyCon wasn't going to be so busy because I didn't submit a talk or tutorial. Ha! What the heck was I thinking? Here's what I've already got in the works. Wednesday, March 7th Me and Audrey are driving up from Los Angeles. I've wanted to do this drive for a while, so this is very exciting. We'll arrive in the evening and hopefully tag up with friends old and new. Thursday, March 8th I'm moderating the Code Reuse panel of the Python Web Summit. Have you submitted a question yet? In the evening we'll be helping assemble bags for the conference. That's always a blast. Friday, March 9th PyCon really begins! I'll be at the keynotes, and then the talks begin. These are some of the talks I'm really leaning towards watching: Introduction to Metaclasses The Art of Subclassing Data, Design, Meaning Code Generation in Python: Dismantling Jinja The problem, of course, is that all the talks look awesome. Missing some of these talks is going to hurt. In the evening we're going to the New Relic/Loggly/Skull Candy party and hang out at the (in)famous TIP BOF. Saturday, March 10th I'll be at … -
My PyCon 2012 Schedule
Here I was thinking that this year's PyCon wasn't going to be so busy because I didn't submit a talk or tutorial. Ha! What the heck was I thinking? Here's what I've already got in the works. Wednesday, March 7th Me and Audrey are driving up from Los Angeles. I've wanted to do this drive for a while, so this is very exciting. We'll arrive in the evening and hopefully tag up with friends old and new. Thursday, March 8th I'm moderating the Code Reuse panel of the Python Web Summit. Have you submitted a question yet? In the evening we'll be helping assemble bags for the conference. That's always a blast. Friday, March 9th PyCon really begins! I'll be at the keynotes, and then the talks begin. These are some of the talks I'm really leaning towards watching: Introduction to Metaclasses The Art of Subclassing Data, Design, Meaning Code Generation in Python: Dismantling Jinja The problem, of course, is that all the talks look awesome. Missing some of these talks is going to hurt. In the evening we're going to the New Relic/Loggly/Skull Candy party and hang out at the (in)famous TIP BOF. Saturday, March 10th I'll be at … -
Django class based views (IV)
Començam a lligar les class views amb els models de dades, que això es posa cada cop més interessant. Fins ara hem vist un ús de les class views molt genèric, és a dir, amb el que sabem podem mostrar planes webs i gestionar el treball amb formularis. Es comú en la majoria d'aplicacions web modernes que les dades venguin d'algún lloc, d'una base de dades per exemple. Així que la gent de Django han creat tota una sèrie de mixin i vistes específices per a simplificar-ne el treball. Mostrar un objecte Suposem que volem mostrar les dades que tenim d'un usuari. Com sabeu el model User de Django conté les dades dels usuaris i es troba a django.contrib.auth.models. Voldríem que en especificar-ne la clau primària a la url poder mostrar les dades de l'usuari corresponent. És a dir, es tracta de mostrar informació que es correspon a urls d'aquest tipus '^prefix/(?P<pk>\d+)/$' o també '^prefix/(?P<slug>[-w]+)/$' Django ens proporciona la classe DetailView per fer precisament això. És a dir, per estalviar-nos la major part de la feina de cercar l'objecte que es correspon amb la clau primària o l'slug i passar-ho a la plantilla per a la seva presentació. Per si … -
Browser ID
Browser ID is Mozillas new federated authentication system. This screencast walks you through using the django-browserid package to do your authentication, and attach it to the built in Django auth systemWatch Now... -
Browser ID
Browser ID is Mozillas new federated authentication system. This screencast walks you through using the django-browserid package to do your authentication, and attach it to the built in Django auth systemWatch Now... -
Selected for PyCon StartUp Row
Me and Audrey have been working hard on Consumer Notebook, a Python/Django based project. We submitted it to PyCon StartUp row and found out this morning we've been accepted. Hooray! From the PyCon StartUp Row winner's post, here is a little bit of what we're about: Have you tried researching products online recently? Search engines are gamed by scammy marketers. Product review sites overwhelm you with ads, have unreliable reviews, or dryly compare raw product specs. Consumer Notebook is working to solve this problem. It is like Yelp for products, with product comparison grids inspired by the founders' open-source work on Django Packages and Open Comparison. Just so you know, PyCon in North America is the biggest gathering for the international Python community. The conference this year is in Santa Clara, California, and is sold-out at 1500+ attendees, but could have easily sold out several times that number. The talks, tutorials, and events are going to be incredible, and I'm delighted to be part of the PyCon experience! We look forward to sharing the StartUp Row with friends like Transifex, Python Packages, and Wedding Lovely. Please check out Consumer Notebook right now and also visit our PyCon booth on Saturday, … -
Selected for PyCon StartUp Row
Me and Audrey have been working hard on Consumer Notebook, a Python/Django based project. We submitted it to PyCon StartUp row and found out this morning we've been accepted. Hooray! From the PyCon StartUp Row winner's post, here is a little bit of what we're about: Have you tried researching products online recently? Search engines are gamed by scammy marketers. Product review sites overwhelm you with ads, have unreliable reviews, or dryly compare raw product specs. Consumer Notebook is working to solve this problem. It is like Yelp for products, with product comparison grids inspired by the founders' open-source work on Django Packages and Open Comparison. Just so you know, PyCon in North America is the biggest gathering for the international Python community. The conference this year is in Santa Clara, California, and is sold-out at 1500+ attendees, but could have easily sold out several times that number. The talks, tutorials, and events are going to be incredible, and I'm delighted to be part of the PyCon experience! We look forward to sharing the StartUp Row with friends like Transifex, Python Packages, and Wedding Lovely. Please check out Consumer Notebook right now and also visit our PyCon booth on Saturday, … -
Django class based views (III)
En aquest apunt veurem com fer servir les generic class views per a fer feina amb formularis. Seguirem la documentació de Django que tracta dels formularis. Allà ens fa referència a un formulari de contacte creat com: from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() cc_myself = forms.BooleanField(required=False) i la vista associada def contact(request): if request.method == 'POST': # If the form has been submitted... form = ContactForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/thanks/') # Redirect after POST else: form = ContactForm() # An unbound form return render_to_response('contact.html', { 'form': form, }) El que farem ara és fer el mateix però fent servir les generic class views. El primer que hem de veure és què hem de fer servir. Necessitam gestionar un formulari, la seva validació i tornar la redirecció cap a una nova plana web en cas que tot vagi bé. Si feim una ullada a la jerarquia de classes del mòdul edit podem veure que la classes que compleix tot el que volem es diu FormView. FormView està composada pel mixin TemplateResponseMixin … -
Django class based views (II)
En aquesta segona part veurem alguns dels usos més interessants de les class based views per a presentar informació i estalviar-nos feina. TemplateView Com ja vàrem veure a la primera part el TemplateView ens estalvia molta feina respecte a la manera tradicional de fer les coses, sols pel fet de passar ja el RequestContext ja recomanaria passar-nos al nou món de les Class Based Views, però encara hi ha més! TemplateView incorpora dos mètodes més get_context_data i get. Amb el get el que fa es cridar al mètode render_to_response que ens proporciona el mixin TemplateResponseMixin i passant-li com a arguments el diccionari que ens ha de tornar el mètode get_context_data. Per defecte get_context_data ens retorna un diccionari amb els paràmetres que venen de la url, així si la nostra url és url(r'^test3/(?P<id>\d+)/$', Test3View.as_view(), name="test3-class-view"), llavors get_context_data conté el diccionari {'id': 3} i a la plantilla es passarà una variable anomenada params amb aquest diccionari. Suposem però que no és això exactament el que volem. Volem que passi a la plantilla una variable anomenanda id amb una salutació per als lectors del blog. El que farem serà sobreescriure get_context_data per a que passi la informació que nosaltres volem a la plantilla. … -
My blog is moved
From now on I'll be blogging from http://pydanny.com.See you there! -
Django class based views (I)
Class based views Amb Django 1.3 s'introdueixen les "Class based views", una funcionalitat que ens permet modelar les nostres vistes com a classes i que a més intenta solucionar el no tenir que escriure sempre el mateix tipus de codi quan mostram una plana web o fem un manteniment lligat a un model de dades. Les class based views ens permeten un nivell més alt de reutilització del nostre codi i a més ens permeten de mantenir-ne la cohesió. Fins ara o bé teníem que anar creant les funcions dins la mateixa vista, dins la mateixa funció o tirar de mòduls independents. Amb les class based views pode anar creant funcions per a la nostra vista, de manera que després sigui més bo de fer reaprofitar-les extenent la classe. En poques paraules, les class based views requereixen un temps d'adaptació i alguns diuen que aprendre un nou DSL (Domain Specific Language). Potser sí, però s'ho paga. Abans de començar Encara que podem utilitzar les nostres pròpies class based views, Django ens dóna ja fetes les més freqüents i un conjunt de classes que podem fer servir en cas que cap ens encaixi. És en aquestes classes on hi ha gran … -
Replacing Redis with a Python Mock
tl;dr When writing tests, mock out a subsystem if and only if it’s prohibitive to test against the real thing. !tl;dr Our product uses Redis. It’s an awesome technology. We’ve avoided needing Redis in our unit tests. But when I added a product feature that made deep use of Redis, I wrote its unit tests to use it, and changed our development fabfile to instantiate a test Redis server when running the unit tests locally. (A QA purest might argue that unit tests should never touch major system components outside of the unit under test. I prefer to do as much testing as possible in unit tests, provided they don’t take too long to run, and setup and teardown aren’t too much of a PITA.) This was a contributory reason for our builds now failing on our Hudson CI server. Redis wasn’t installed on it! Why didn’t I immediately install Redis on our CI server? Our CI server had other problems I intended to nuke it and re-create it with the latest version of Jenkins. I just needed to first clear some things off my plate Our dev team had shrunk down to just two people We were both strict … -
Font size feedback wanted
-
django-uni-form end of life
I started on django-uni-form in January 2009. In order to use Pinax on an internal social network for NASA HQ, we had to render all content, including forms, Section 508 compliant. Rather than rewrite the html for all 50+ forms that existed in the Pinax 0.5.x framework at that time, I decided to minimize my work and automate things. James Tauber gave guidance and insight, my co-workers were supportive, and Jannis Leidel suggested the Uni-form library. The name Django Uni-Form was obvious, and lo the project was named. Looking at the old, extremely deprecated Google Code site for django-uni-form, I see that the first commit happened on January 7th, 2009. That was for version 0.1, with some core code that was literally a merger between the Django form example on how to integrate divs into forms and the simplest template tag I could figure out. The python code in uni_form/templatetags/uni_form.py: from django.template import Context, Template from django.template.loader import get_template from django import template register = template.Library() @register.filter def as_uni_form(form): template = get_template('templates/uni_form.html') c = Context({'form':form}) return template.render(c) The template tag code was nearly exactly copy/pasted from the starter Django docs on forms: {% for field in form %} <div class="ctrlHolder … -
django-uni-form end of life
I started on django-uni-form in January 2009. In order to use Pinax on an internal social network for NASA HQ, we had to render all content, including forms, Section 508 compliant. Rather than rewrite the html for all 50+ forms that existed in the Pinax 0.5.x framework at that time, I decided to minimize my work and automate things. James Tauber gave guidance and insight, my co-workers were supportive, and Jannis Leidel suggested the Uni-form library. The name Django Uni-Form was obvious, and lo the project was named. Looking at the old, extremely deprecated Google Code site for django-uni-form, I see that the first commit happened on January 7th, 2009. That was for version 0.1, with some core code that was literally a merger between the Django form example on how to integrate divs into forms and the simplest template tag I could figure out. The python code in uni_form/templatetags/uni_form.py: from django.template import Context, Template from django.template.loader import get_template from django import template register = template.Library() @register.filter def as_uni_form(form): template = get_template('templates/uni_form.html') c = Context({'form':form}) return template.render(c) The template tag code was nearly exactly copy/pasted from the starter Django docs on forms: {% for field in form %} <div class="ctrlHolder … -
Satchmo Diaries
Bob Waycott from Medium Labs has written some great articles on customizing Satchmo. -
Using Django Permissions
I recently had the need to use the Django permission system and couple it with newforms admin. There were a couple of tricks in the process so hopefully this will be useful for you. -
Satchmo 0.8 Release
After 6 months of development activity, Satchmo 0.8 is now released and represents the first official Satchmo release that is compatible with Django 1.0. -
Satchmo DjangoCon Video Available
The satchmo YouTube video and presentation from Djangocon are now available. -
Thoughts from DjangoCon 2008
I'm back from Djangocon and wanted to write up a few notes regarding the trip. Like most people have already commented, Djangocon was a great conference. The talks were almost universally well done - interesting, engaging and I had some good learning from almost every one... -
Django 1.4 beta 1 lançado
Django 1.4 beta 1 lançado