Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
DiamondHacks 2015 Recap
Image via Diamond Hacks Facebook Page This past weekend, Technical Director Mark Lavin came out to support DiamondHacks, NCSU’s first ever hackathon and conference event for women interested in computer science. Not only is NCSU Mark’s alma mater, but he’s also a strong supporter of co-organizer Girl Develop It RDU (GDI), of which Caktus is an official sponsor. The weekend’s events began Saturday with nervous excitement as Facebook developer Erin Summers took the stage for her keynote address. Most memorable for Mark was a moment towards the end of Summers’ talk, in which she called for collaboration between neighboring audience members. It was at this point Mark first realized he was the only male in the room—a unique experience for a male developer. “I’m sure there’s lots of women who have felt the way I did,” Mark commented. The moment not only flipped the norms of a traditionally male-dominated field, but also filled Mark with a renewed appreciation for the importance of active inclusivity in the tech industry. Aside from helping fill swag bags for the weekend’s participants and attending several of the talks, Mark gave a lightning talk, “Python and Django: Web Development Batteries Included” on Python and Django. … -
DiamondHacks 2015 Recap
Image via Diamond Hacks Facebook Page This past weekend, Technical Director Mark Lavin came out to support DiamondHacks, NCSU’s first ever hackathon and conference event for women interested in computer science. Not only is NCSU Mark’s alma mater, but he’s also a strong supporter of co-organizer Girl Develop It RDU (GDI), of which Caktus is an official sponsor. The weekend’s events began Saturday with nervous excitement as Facebook developer Erin Summers took the stage for her keynote address. Most memorable for Mark was a moment towards the end of Summers’ talk, in which she called for collaboration between neighboring audience members. It was at this point Mark first realized he was the only male in the room—a unique experience for a male developer. “I’m sure there’s lots of women who have felt the way I did,” Mark commented. The moment not only flipped the norms of a traditionally male-dominated field, but also filled Mark with a renewed appreciation for the importance of active inclusivity in the tech industry. Aside from helping fill swag bags for the weekend’s participants and attending several of the talks, Mark gave a lightning talk, “Python and Django: Web Development Batteries Included” on Python and Django. … -
Django, pytz, NonExistentTimeError and AmbiguousTimeError
Brief: In one of the project I work on we had to convert some old naive datetime objects to timezone aware ones. Converting naive datetime to timezone aware one is usually a straightforward job. In django you even have a nice utility function for this. For example: import pytz from django.utils import timezone timezone.make_aware(datetime.datetime(2012, 3, 25, 3, 52), timezone=pytz.timezone('Europe/Stockholm')) # returns datetime.datetime(2012, 3, 25, 3, 52, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>) Problem: You can use this for quite a long time until one day you end up with something like this: timezone.make_aware(datetime.datetime(2012, 3, 25, 2, 52), timezone=pytz.timezone('Europe/Stockholm')) # which leads to Traceback (most recent call last): File "", line 1, in File "/home/ilian/venvs/test/lib/python3.4/site-packages/django/utils/timezone.py", line 358, in make_aware return timezone.localize(value, is_dst=None) File "/home/ilian/venvs/test/lib/python3.4/site-packages/pytz/tzinfo.py", line 327, in localize raise NonExistentTimeError(dt) pytz.exceptions.NonExistentTimeError: 2012-03-25 02:52:00 Or this: timezone.make_aware(datetime.datetime(2012, 10, 28, 2, 52), timezone=pytz.timezone('Europe/Stockholm')) #throws Traceback (most recent call last): File "", line 1, in File "/home/ilian/venvs/test/lib/python3.4/site-packages/django/utils/timezone.py", line 358, in make_aware return timezone.localize(value, is_dst=None) File "/home/ilian/venvs/test/lib/python3.4/site-packages/pytz/tzinfo.py", line 349, in localize raise AmbiguousTimeError(dt) pytz.exceptions.AmbiguousTimeError: 2012-10-28 02:52:00 Explanation: The reason for the first error is that in the real world this datetime does not exists. Due to the DST change on this date the clock jumps from 01:59 … -
Django, pytz and NonExistentTimeError
Brief: In one of the project I work on we have convert some old naive datetime object to timezone aware ones. Converting naive datetime to timezone aware one is usually straightforward job. In django you even have a nice utility function for this. For example: import pytz from django.utils import timezone timezone.make_aware(datetime.datetime(2012, 3, 25, 3, 52), timezone=pytz.timezone('Europe/Stockholm')) # returns datetime.datetime(2012, 3, 25, 3, 52, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>) Problem: You can use this for quite a long time until one day you end up with something like this: timezone.make_aware(datetime.datetime(2012, 3, 25, 2, 52), timezone=pytz.timezone('Europe/Stockholm')) # which leads to Traceback (most recent call last): File "", line 1, in File "/home/ilian/venvs/test/lib/python3.4/site-packages/django/utils/timezone.py", line 358, in make_aware return timezone.localize(value, is_dst=None) File "/home/ilian/venvs/test/lib/python3.4/site-packages/pytz/tzinfo.py", line 327, in localize raise NonExistentTimeError(dt) pytz.exceptions.NonExistentTimeError: 2012-03-25 02:52:00 Explanation: The reason for this error is that in the real world this datetime does not exists. Due to the DST change on this date the clock jumps from 01:59 directly to 03:00. Fortunately (or not) pytz is aware of the fact that this time is invalid and will throw the exception above. Why this happens? Well we couldn't be sure how exactly this one got into our legacy data but the … -
Tastypie with ForeignKey
Tastypie with ForeignKeys This is a followup post on Getting started with tastypie. We will use the same project setup as used in the last post. This post will cover: Fetch ForeignKey data in GET calls Create an object with ForeignKeys using POST calls Setup the application Let's add the capability to categorise the expenses Add a model called ExpenseCategory class ExpenseCategory(models.Model): name = models.CharField(max_length=100) description = models.TextField() Add a FK from Expense to ExpenseCategory class Expense(models.Model): description = models.CharField(max_length=100) amount = models.IntegerField() user = models.ForeignKey(User, null=True) category = models.ForeignKey(ExpenseCategory, null=True) There already exists some Expense in db without an associated category, so make ExpenseCategory as nullable. Create and apply migrations python manage.py makemigrations python manage.py migrate Let's create an expensecategory from shell and associate it with an expense of user Sheryl. u = User.objects.get(username='sheryl') ec = ExpenseCategory.objects.create(name='Misc', description='Miscellaneous expenses') e = Expense.objects.create(description='Went to Stockholm', amount='5000', user=u, category=ec) Get FK fields in response too. We want category in Expense GET endpoint too. Our first approach would be adding 'category' to ExpenseCategory.Meta.fields. Try it fields = ['description', 'amount', 'category'] Try the expense GET endpoint for Sheryl http://localhost:8000/api/expense/?username=sheryl&api_key=1a23&format=json Still don't see category in response. We need something more than this. Adding fields.ForeignKey … -
Welcome to Our New Staff Members
We’ve hit one of our greatest growth points yet in 2015, adding nine new team members since January to handle our increasing project load. There are many exciting things on the horizon for Caktus and our clients, so it’s wonderful to have a few more hands on deck. One of the best things about working at Caktus is the diversity of our staff’s interests and backgrounds. In order of their appearance from left to right in the photos above, here’s a quick look at our new Cakti’s roles and some fun facts: Neil Ashton Neil was also a Caktus contractor who has made the move to full-time Django developer. He is a keen student of more than programming languages; he holds two degrees in Classics and another Master’s in Linguistics. Jeff Bradberry Though Jeff has been working as a contractor at Caktus, he recently became a full-time developer. In his spare time, he likes to play around with artificial intelligence, sometimes giving his creations a dose of inexplicable, random behavior to better mimic us poor humans. Ross Pike Ross is our new Lead Designer and has earned recognition for his work from Print, How Magazine, and the AIGA. He also … -
Welcome to Our New Staff Members
We’ve hit one of our greatest growth points yet in 2015, adding nine new team members since January to handle our increasing project load. There are many exciting things on the horizon for Caktus and our clients, so it’s wonderful to have a few more hands on deck. One of the best things about working at Caktus is the diversity of our staff’s interests and backgrounds. In order of their appearance from left to right in the photos above, here’s a quick look at our new Cakti’s roles and some fun facts: Neil Ashton Neil was also a Caktus contractor who has made the move to full-time Django developer. He is a keen student of more than programming languages; he holds two degrees in Classics and another Master’s in Linguistics. Jeff Bradberry Though Jeff has been working as a contractor at Caktus, he recently became a full-time developer. In his spare time, he likes to play around with artificial intelligence, sometimes giving his creations a dose of inexplicable, random behavior to better mimic us poor humans. Ross Pike Ross is our new Lead Designer and has earned recognition for his work from Print, How Magazine, and the AIGA. He also … -
High Performance Django Infrastructure Preview
One of the most common requests we've heard since releasing our book, High Performance Django is: "Do you have more code/configuration examples?" It's a pretty loaded question because the book covers everything from Python code to deploying and configuring servers. After some thinking on how to deliver this in a format people could easily understand, I realized the answer was already right under our noses. We've been users of Salt for configuration management for almost three years. Over the last few weeks I've been extracting our internal Salt states into a reusable and extensible system I like to call "infrastructure-in-a-box". It encompasses all the lessons we've learned over the years with our different clients and allows anyone to setup a complete Python website (load balancer, web accelerator, cache, database, task queue, etc.) in about 15 minutes. The exact same code can be used to setup a single Vagrant machine on your laptop or a ten server farm in the cloud. I whipped together a quick screencast preview of it in action (apologies for the low-quality audio): I'm really excited about being able to offer this as a companion product to our book. It's going to save people a lot of … -
RevSys Roundup - March 2015
RevSys Roundup - March 2015 -
Twitter way back machine
One of the associates at Techstars created this beautiful demo of Stream’s technology (github repo). If you ever wondered about Thomas Edison’s or Nikola Tesla’s tweets, check it out! :) Share and Enjoy: -
Getting started with Django tastypie
Django tastypie is a library to write RESTful apis in Django. Why use REST You have a database backed web application. This application tracks expenses. The application allows the capability to enter your expenses, view all your expenses, delete an expense etc. Essentially this application provides CRUD functionality. Django application has access to database credentials, but they are never seen by the users of the web application. Django application decides what to show to which user. Django application ensures that a particular user only sees the expenses entered by him and not somebody else's expenses. Now you want to provide a mobile application (Android or iOS) corresponding to this web application. Android application should allow the user to view his expenses, create an expense as well as any other CRUD functionality. But database credentials could not be put in Android code as it is not too hard to decompile an apk and get the db credentials. And we never want a user to get the db credentials else he will be in a position to see everyone's expenses and the entire database. So there has to be another way to allow mobile applications to get things from the database. This … -
Astro Code School Now Accepting Applications - Intermediate Django + Python
I'm really happy to officially announce the first Python and Django Web Engineering class at Astro Code School. I’ll outline some details here and you can also find them on our classes page. This class is twelve weeks long and full time Monday to Friday from 9 AM – 5 PM. It'll be taught here at the Astro Code School at 108 Morris Street, Suite 1b, Durham, NC. We will conduct two Python and Django Web Engineering classes in 2015. The first one in term two starts May 18, 2015 and ends August 10, 2015. The second one in term three starts September 22, 2015 and ends December 15, 2015. Enrollment for both sections opens today March 20. There is space for twelve students in each class. More information about the enrollment process is on our Apply page. Part of that process is an entrance exam that is designed to ensure you're ready to succeed. The price per person for Python and Django Web Engineering is $12,000. The Python and Django Web Engineering class is intended for intermediate level students. Its goal is to help you start your career as a backend web engineer. To start down this … -
Astro Code School Now Accepting Applications - Intermediate Django + Python
I'm really happy to officially announce the first Python and Django Web Engineering class at Astro Code School. I’ll outline some details here and you can also find them on our classes page. This class is twelve weeks long and full time Monday to Friday from 9 AM – 5 PM. It'll be taught here at the Astro Code School at 108 Morris Street, Suite 1b, Durham, NC. We will conduct two Python and Django Web Engineering classes in 2015. The first one in term two starts May 18, 2015 and ends August 10, 2015. The second one in term three starts September 22, 2015 and ends December 15, 2015. Enrollment for both sections opens today March 20. There is space for twelve students in each class. More information about the enrollment process is on our Apply page. Part of that process is an entrance exam that is designed to ensure you're ready to succeed. The price per person for Python and Django Web Engineering is $12,000. The Python and Django Web Engineering class is intended for intermediate level students. Its goal is to help you start your career as a backend web engineer. To start down this … -
Test django view with cookies
To test some view which use cookies: 1 2 3 4 5 6 7 8 9 10 from Cookie import SimpleCookie from django import test class SomeTest(test.TestCase): def test_some_view(self): self.client.cookies = SimpleCookie({'test_cookie': 'test_value'}) response = self.client.get('/some-url/') self.assertEqual(response.client.cookies['test_cookie'].value, 'test_value') -
Django Gotchas #1 - Dynamic Initial Values In Forms!
Django form fields accept initial argument. So You can set a default value for a field.Sometimes it is required to override __init__ method in forms and set field initial arguments.Now let's pass some initial data to form and see what happens.If You look at the value of input field, it's is NOT the overrided. It still has form initial value! If You look into source code of django forms to find what is happening, You will find this.So form's initial value has precedence over fields initial values.So You have to override form's initial value instead of fields's initial value to make it work as expected.Read official docs about django forms.Read more articles about Python! -
Django Tips & Tricks #3 - Dynamic Initial Values In Forms
Django form fields accept initial argument. So You can set a default value for a field. In [1]: from django import forms In [2]: class SampleForm(forms.Form): ...: name = forms.CharField(max_length=10, initial='avil page') ...: In [3]: f = SampleForm() In [4]: f.as_p() Out[4]: u'<p>Name: <input maxlength="10" name="name" type="text" value="avil page" /></p>' Sometimes it is required to override init method in forms and set field initial arguments. In [11]: from django import forms In [12]: class AdvancedForm(forms.Form): ....: ....: def __init__(self, *args, **kwargs): ....: super().__init__(*args, **kwargs) ....: self.fields['name'].initial = 'override' ....: ....: name=forms.CharField(max_length=10) ....: In [13]: f2 = AdvancedForm() In [14]: f2.as_p() Out[14]: '<p>Name: <input maxlength="10" name="name" type="text" value="override" /></p>' Now let's pass some initial data to form and see what happens. In [11]: from django import forms In [12]: class AdvancedForm(forms.Form): ....: ....: def __init__(self, *args, **kwargs): ....: super().__init__(*args, **kwargs) ....: self.fields['name'].initial = 'override' # don't try this at home ....: ....: name=forms.CharField(max_length=10) ....: In [19]: f3 = AdvancedForm(initial={'name': 'precedence'}) In [20]: f3.as_p() Out[20]: '<p>Name: <input maxlength="10" name="name" type="text" value="precedence" /></p>' If You look at the value of input field, it's is NOT the overrided. It still has form initial value! If You look into source code of django forms to … -
Why RapidSMS for SMS Application Development
Caktus has been involved in quite a few projects (Libyan voter registration, UNICEF Project Mwana, and several others) that include text messaging (a.k.a. Short Message Service, or SMS), and we always use RapidSMS as one of our tools. We've also invested our own resources in supporting and extending RapidSMS. There are other options; why do we consistently choose RapidSMS? What is RapidSMS First, what is RapidSMS? It's an open source package of useful tools that extend the Django web development framework to support processing text messages. It includes: A framework for writing code to be invoked when a text message is received and respond to it A set of backends - pluggable code modules that can interface to various ways of connecting your Django program to the phone network to pass text messages back and forth Sample applications Documentation The backends are required because unlike email, there's no universal standard for sending and receiving text messages over the Internet. Often we get access to the messages via a third party vendor, like Twilio or Tropo, that provides a proprietary interface. RapidSMS isolates us from the differences among vendors. RapidSMS is open source, under the BSD license, with UNICEF acting as … -
Why RapidSMS for SMS Application Development
Caktus has been involved in quite a few projects (Libyan voter registration, UNICEF Project Mwana, and several others) that include text messaging (a.k.a. Short Message Service, or SMS), and we always use RapidSMS as one of our tools. We've also invested our own resources in supporting and extending RapidSMS. There are other options; why do we consistently choose RapidSMS? What is RapidSMS First, what is RapidSMS? It's an open source package of useful tools that extend the Django web development framework to support processing text messages. It includes: A framework for writing code to be invoked when a text message is received and respond to it A set of backends - pluggable code modules that can interface to various ways of connecting your Django program to the phone network to pass text messages back and forth Sample applications Documentation The backends are required because unlike email, there's no universal standard for sending and receiving text messages over the Internet. Often we get access to the messages via a third party vendor, like Twilio or Tropo, that provides a proprietary interface. RapidSMS isolates us from the differences among vendors. RapidSMS is open source, under the BSD license, with UNICEF acting as … -
My approach to Class Based Views
I've written in the past about my dislike for Django's Class Based Views. Django's CBVs add a lot of complexity and verbosity, and simply get in the way of some moderately common patterns (e.g. when you have two forms in a single view). It seems I'm not alone as a Django core dev who thinks that way. In this post, however, I'll write about a different approach that I took in one project, which can be summed up like this: Write your own base class. For really simple model views, Django's own CBVs can be a time saver. For anything more complex, you will run into difficulties, and will need some heavy documentation at the very least. One solution is to use a simplified re-implementation of Class Based Views. My own approach is to go even further and start from nothing, writing your own base class, while borrowing the best ideas and incorporating only what you need. Steal the good ideas The as_view method provided by the Django's View class is a great idea — while it may not be obvious, it was hammered out after a lot of discussion as a way to help promote request isolation by creating … -
Saving processes and threads in a WSGI server with Moya
I have a webserver with 3 WSGI applications running on different domains (1, 2, 3). All deployed with a combination of Gunicorn and NGINX. A combination that works really well, but there are two annoyances that are only going to get worse the more sites I deploy: A) The configuration for each server resides in a different location on the filesystem, so I have to recall & type a long path to edit settings. B) More significantly, each server adds extra resource requirements. I follow the advice of running each WSGI application with (2 * number_of_cores + 1) processes, each with 8 threads. The threads may be overkill, but that ensures that the server can use all available capacity to handle dynamic requests. On my 4 core server, that's 9 processes, 72 threads per site. Or 27 processes, and 216 threads for the 3 sites. I suspect that is too many resources. A new feature recently added to Moya fixes both those problems. Rather than deploy a WSGI application for each site, Moya can now optionally create a single WSGI application that serves many sites. With this new system, configuration is read from /etc/moya/, which contains a directory structure like … -
Saving processes and threads in a WSGI server with Moya
I have a webserver with 3 WSGI applications running on different domains (1, 2, 3). All deployed with a combination of Gunicorn and NGINX. A combination that works really well, but there are two annoyances that are only going to get worse the more sites I deploy: A) The configuration for each server resides in a different location on the filesystem, so I have to recall & type a long path to edit settings. B) More significantly, each server adds extra resource requirements. I follow the advice of running each WSGI application with (2 * number_of_cores + 1) processes, each with 8 threads. The threads may be overkill, but that ensures that the server can use all available capacity to handle dynamic requests. On my 4 core server, that's 9 processes, 72 threads per site. Or 27 processes, and 216 threads for the 3 sites. Clearly that's not scalable if I want to host more web applications on one server. A new feature recently added to Moya fixes both those problems. Rather than deploy a WSGI application for each site, Moya can now optionally create a single WSGI application that serves many sites. With this new system, configuration is read … -
Saving processes and threads in a WSGI server with Moya
I have a webserver with 3 WSGI applications running on different domains (1, 2, 3). All deployed with a combination of Gunicorn and NGINX. A combination that works really well, but there are two annoyances that are only going to get worse the more sites I deploy: A) The configuration for each server resides in a different location on the filesystem, so I have to recall & type a long path to edit settings. B) More significantly, each server adds extra resource requirements. I follow the advice of running each WSGI application with (2 * number_of_cores + 1) processes, each with 8 threads. The threads may be overkill, but that ensures that the server can use all available capacity to handle dynamic requests. On my 4 core server, that's 9 processes, 72 threads per site. Or 27 processes, and 216 threads for the 3 sites. Clearly that's not scalable if I want to host more web applications on one server. A new feature recently added to Moya fixes both those problems. Rather than deploy a WSGI application for each site, Moya can now optionally create a single WSGI application that serves many sites. With this new system, configuration is read … -
Documenting Python without Sphinx
Last week Evennia merged its development branch with all the features mentioned in the last post. Post-merger we have since gone through and fixed remaining bugs and shortened the list at a good clip. One thing I have been considering is how to make Evennia's API auto-documenting - we are after all a MUD creation library and whereas our code has always been well-documented the docs were always only accessible from the source files themselves.Now, when you hear "Python" and "documentation" in the same sentence, the first thought usually involves Sphinx or Sphinx autodoc in some form. Sphinx produces very nice looking documentation indeed. My problem is however as follows:I don't want our API documentation to be written in a different format from the rest of our documentation, which is in Github's wiki using Markdown. Our users should be able to help document Evennia without remembering which formatting language is to be used.I don't like reStructuredText syntax. This is a personal thing. I get that it is powerful but it is also really, really ugly to read in its raw form in the source code. I feel the sources must be easy to read on their own. Sphinx plugins like … -
How to build a notification feed using Stream
Tommaso wrote a quick tutorial on how to build a notification feed using Django and Stream. How to build a notification feed using Stream. Share and Enjoy: -
Connecting Django Models with outer applications
Preface: Sometimes, parts of the data that you have to display in your application reside out of the Django models. Simple example for this is the following case - the client requires that you build them a webshop but they already have CRM solution that holds their products info. Of course they provide you with a mechanism to read this data from their CRM. Specialty: The problem is that the data in their CRM does not hold some of the product information that you need. For instance it misses SEO-friendly description and product image. So you will have to set up a model at your side and store these images there. It is easy to join them, the only thing that you will need is a simple unique key for every product. Solution: Here we use the product_id field to make the connection between the CRM data and the Django model. # in models.py class Product(models.Model): product_id = models.IntegerField(_('Original Product'), unique=True) description = models.TextField(_('SEO-friendly Description'), blank=True) pod_image = FilerImageField(verbose_name=_('Product Image'), blank=True, null=True) @property def name(self): return crm_api.get_product_name(self.product_id) # in forms.py class ProductForm(forms.ModelForm): name = forms.CharField(required=False, widget=forms.TextInput(attrs={ 'readonly': True, 'style': 'border: none'})) class Meta: model = Product widgets = { 'product_id': …