Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
django-registration
I mentioned a couple weeks ago that lately I’ve been in the process of providing updated releases for all the various open-source projects I maintain, and specifically mentioned a desire to resurrect django-registration which, once upon a time, was the most popular thing I’d ever written. Over the past week I’ve been focusing more heavily on that, and now it’s time to start talking about a release. Ancient history I’ve always felt pretty strongly that Django’s killer ... Read full entry -
django-registration
I mentioned a couple weeks ago that lately I’ve been in the process of providing updated releases for all the various open-source projects I maintain, and specifically mentioned a desire to resurrect django-registration which, once upon a time, was the most popular thing I’d ever written. Over the past week I’ve been focusing more heavily on that, and now it’s time to start talking about a release. Ancient history I’ve always felt pretty strongly that Django’s killer ... Read full entry -
Amazon SES - Handling Bounces and Complaints.
Why do we go for Bounce and Complaint Handling while sending mails? In general while sending emails, we will prepare some recipient addresses as our mailing list, which are valid and our recipients want and expect our mail. But some times, some emails which are invalid will bounce, and if valid recipients do not want your mail, they may mark your email as spam in their email client. High bounce and complaint rates put your account at risk of being shut down. So in order to avoid such problem we'll handle the bounces and complaints and will remove those emails for not sending any mails further. Flow of Bounce and Complaint handling in AWS using SNS: In order to handle bounces and notifications AWS provides a service called SNS(Simple Notification Service). Using this feature we can handle bounces or complaints by configuring an webhook end point or email or using amazon's SQS service. As Django developers we'll try to know of how to handle bouce or complaints using webhooks in the current blog post. For this we'll use amazon's boto package as development API. 1. First we need to create an SNS Topic. An SNS Topic is a communication channel to … -
Amazon SES - Handling Bounces and Complaints.
Why do we go for Bounce and Complaint Handling while sending mails? In general while sending emails, we will prepare some recipient addresses as our mailing list, which are valid and our recipients want and expect our mail. But some times, some emails which are invalid will bounce, and if valid recipients do not want your mail, they may mark your email as spam in their email client. High bounce and complaint rates put your account at risk of being shut down. So in order to avoid such problem we'll handle the bounces and complaints and will remove those emails for not sending any mails further. Flow of Bounce and Complaint handling in AWS using SNS: In order to handle bounces and notifications AWS provides a service called SNS(Simple Notification Service). Using this feature we can handle bounces or complaints by configuring an webhook end point or email or using amazon's SQS service. As Django developers we'll try to know of how to handle bouce or complaints using webhooks in the current blog post. For this we'll use amazon's boto package as development API. 1. First we need to create an SNS Topic. An SNS Topic is a communication channel to … -
Improving page speed score in Google Page Score test- PART2
In our previous blog post we got an idea of what are the things that Google's Page Speed Insights will take into count to give page socre, now in the present blog post we'll get to know what are the techniques we can use to improve the page scrore. 1. Reducing the Server response time: As a programmer one of the reasons of the high server response time is due to redundancy in the queries. The following the cases where we use redundancy of queries and how can we reduce them. We use .exists() method, while querying to check if the DB object exists or not. Suppose we are having a model called 'Assessment'. The following is a code snippet with wrong usage of .exists(). if Assessment.objects.filter(id=assess.assessment_id, edu_class_id=role.edu_class_id, subject_id=role.subject_id).exists(): assessments_list = assessments_list + list(Assessment.objects.filter(id=assess.assessment_id,edu_class_id=role.edu_class_id,subject_id=role.subject_id)) In the above code the query 'Assessment.objects.filter(id=assess.assessment_id, edu_class_id=role.edu_class_id, subject_id=role.subject_id)' is repeated twice. Using the same query second time is of no use. The method .exists(), is to be used in such caases where the queryset result is not used anywhere else. We can rewrite the above code as below. assessments = Assessment.objects.filter(id=assess.assessment_id, edu_class_id=role.edu_class_id, subject_id=role.subject_id) if assessments: assessments_list = assessments_list + list(assessments) Similarly … -
Improving page speed score in Google Page Score test- PART2
In our previous blog post, we got an idea of what are the things that Google's Page Speed Insights will take into the count to give page score, now in the present blog post we'll get to know what are the techniques we can use to improve the page score. 1. Reducing the Server response time: As a programmer, one of the reasons of the high server response time is due to redundancy in the queries. The following the cases where we use redundancy of queries and how can we reduce them. We use .exists() method, while querying to check if the DB object exists or not. Suppose we are having a model called 'Assessment'. The following is a code snippet with the wrong usage of .exists(). if Assessment.objects.filter(id=assess.assessment_id, edu_class_id=role.edu_class_id, subject_id=role.subject_id).exists(): assessments_list = assessments_list + list(Assessment.objects.filter(id=assess.assessment_id,edu_class_id=role.edu_class_id,subject_id=role.subject_id)) In the above code the query 'Assessment.objects.filter(id=assess.assessment_id, edu_class_id=role.edu_class_id, subject_id=role.subject_id)' is repeated twice. Using the same query second time is of no use. The method .exists(), is to be used in such cases where the query set result is not used anywhere else. We can rewrite the above code as below. assessments = Assessment.objects.filter(id=assess.assessment_id, edu_class_id=role.edu_class_id, subject_id=role.subject_id) if assessments: assessments_list = assessments_list + … -
AWS load balancers with Django
We recently had occasion to reconfigure some of our existing servers to use Amazon Web Services Elastic Load Balancers in front of them. Setting this up isn't hard, exactly, but there are a lot of moving parts that have to mesh correctly before things start to work, so I thought I'd write down what we did. All of these tools have lots of options and ways to use them. I'm not trying to cover all the possibilities here. I'm just showing what we ended up doing. Our requirements We had some specific goals we wanted to achieve in this reconfiguration. There should be no outside requests sneaking in -- the only requests that should reach the backend servers are those that come through the load balancer. We'll achieve this by setting the backend servers' security group(s) to only allow incoming traffic on those ports from the load balancer's security group. The site should only handle requests that have the right Host header. We achieve this already by Nginx configuration (server_name) and won't have to change anything. Redirect any non-SSL requests to SSL. The load balancer can't do this for us (as far as I could see), so we just forward … -
Check out PyCon PL 2015 agenda
The PyCon PL 2015 will be held in Hotel Ossa Congress & Spa located in Ossa on October 15th through October 18th. The conference is held in Poland but consists of two blocks of talks - English and Polish, so non-Polish speaking attendees can benefit from it too. The agenda and other details can be found on the conference website. -
Working with Environment Variables in Python
If you look at modern code deployment practices, like in the 12 factor app, environment variables are very important for keeping secret information secret, or server specific information set for that server. All while not having long crazy settings in a settings file for every single server and computer. It helps keep things slimmer in your code along with the following quoted from the 12factorapp site: * Resource handles to the database, Memcached, and other backing services * Credentials to external services such as Amazon S3 or Twitter * Per-deploy values such as the canonical hostname for the deploy What Are Environment Variables? Environment variables are a key value pairs that can affect how a program runs. They need to be set at some point before a process is run so the process can read them in and act accordingly. A lot of times in production environments your database name and password are set as environment variables so that information does not end up in a code repository somewhere. By relying on an environment variable your code doesn't care what a setting is because you can set that at some other point. Actually working with environment variables is really simple. … -
Announcing the Caktus Open Source Fellowship
We are excited to announce the creation of a pilot program for open source contributions here at Caktus Group. This program is inspired by the Django Software Foundation’s fellowship as well as the Two Day Manifesto. For this program, Caktus seeks to hire a part-time developer for twelve weeks this fall for the sole purpose of contributing back to open source projects. Caktus builds web applications based on open source tools and the continued growth of these projects is important to us. Open source projects such as Python and Django have given so much to this company and this is one of many ways we are trying to give back. We are looking for candidates who would love to collaborate with us in our offices in downtown Durham, NC to directly contribute to both open source projects created at Caktus as well as open source projects used by Caktus, such as Django. As previously mentioned, this will be a part-time position and will be taking the place of our normal fall internship program. If successful, we may expand this into a full-time position for future iterations. I think this will be a great opportunity for a developer to get experience … -
Template fragment caching gotchas
Variables in cached template fragment Assuming this is in template. {% cache 300 nums %} {% for i in nums %} <p>i</p> {% endfor %} {% endcache %} And assuming we send {'nums': range(100)} from context, then 0 to 99 will be sent in the response. Now suppose we change context to {'nums': range(1000)}, still for next 5 minutes i.e until the cache expires, 0 to 99 will be sent in the response. 0 to 999 will not be sent in the response. To fix this, we should use the variable too with the {% cache %} tag. So correct code would be {% cache 300 nums_cache nums %} {% for i in nums %} <p>i</p> {% endfor %} {% endcache %} After this whenever context nums changes, cache would be reevaluated. Boolean variable in cached template fragment Assuming template contains {% cache 300 hello %} {% if hello %} <p>Hello</p> {% endif %} {% endcache %} and assuming {'hello': True} is sent in context. Then <p>Hello</p> will be sent in response. Now even when we send {'hello': False} in context, "<p>Hello</p>" will still be sent in response because it's already cached. To fix this. {% cache 300 hello_cache hello … -
Announcing Django Girls RDU: Free Coding Workshop for Women
We’re incredibly excited to announce the launch of Django Girls RDU, a group in NC’s Triangle region that hosts free one-day Django coding workshops for women. Django Girls is part of an international movement that’s helped 1,600 (and counting!) women learn how to code. We originally got involved with Django Girls at the impetus of our Technical Director, Mark Lavin. While discussing our efforts to support women in tech, Mark was emphatic: there was this group, Django Girls, that was doing extraordinary work engaging women in Django. Clearly, we needed something like that locally. Luckily for us, Django Girls was coming to PyCon and we'd get to see first hand just how wonderful they are. Four of our team members volunteered as coaches for a Django Girls workshop during PyCon 2015. There was nothing quite like seeing the impact Django Girls had on each attendee. The environment was warm, friendly, and infectiously enthusiastic. The tutorials for students, coaches, and organizers, were very thoughtful and detailed. The passion of the Django Girls organizers was evident in every moment. Out of a desire to prolong this excitement and share it with everyone we knew, we put together a team and applied to … -
[Django Tips] Use for ... empty in Django templates.
It is quite common to send a query set from a view to template, loop over it and display items in it. If no items are there, it is good if we display some message. For that we can do something like this.{% if books %} {% for book in books %} <li>{{ book }}</li> {% endfor %}{% else %} <li>Sorry, there are no books.</li>{% endif %}Django {% for %} tag takes an optional {% empty %} clause which will be rendered when queryset is empty. So we can rewrite the above code as{% for book in books %} <li>{{ book }}</li>{% empty %} <li>Sorry, there are no books.</li>{% endfor %}This code is much cleaner than previous one. I tried to profile both code blocks. The first block took 0.9ms and second block took 0.8ms which means it is 11% faster than previous code :)Reference: Django docsRead more articles about Python!Read more articles about Django! -
Django Tips & Tricks #5 - Use for...empty in Django templates
It is quite common to send a query set from a view to template, loop over it and display items in it. If no items are there, it is good if we display some message. For that we can do something like this.{% if books %} {% for book in books %} <li>{{ book }}</li> {% endfor %}{% else %} <li>Sorry, there are no books.</li>{% endif %}Django {% for %} tag takes an optional {% empty %} clause which will be rendered when queryset is empty. So we can rewrite the above code as{% for book in books %} <li>{{ book }}</li>{% empty %} <li>Sorry, there are no books.</li>{% endfor %}This code is much cleaner than previous one. I tried to profile both code blocks. The first block took 0.9ms and second block took 0.8ms which means it is 11% faster than previous code :)Reference: Django docs -
Understanding 'GenericForeignKey' in Django
In some cases the we might want to store generic model object, rather a particular specific model as 'ForeignKey'. Here is scenario of such kind. Suppose there are models like User, Project, Ticket and TimeLine as below. class Ticket(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Project(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class User(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Timeline(models.Model): involved_object = ***** event_type = models.CharField(max_length=250, default="created") If we want to store the user activities with these models like "created User, created Project, created Task" in time line, we have to create all the three models(User, Project, Task) as 'ForeignKey' fields. This is not a good programming practice. To overcome this, Django's contenttypes framework provides a special field type (GenericForeignKey) which allows the relationship to be with any model. Using 'GenericForeignKey' : Here is the solution for the above scenario. There are three parts to setting up a GenericForeignKey: Give your model a ForeignKey to ContentType. The usual name for this field is “content_type”. Give your model a field that can store primary key values from the models you’ll be relating to. For … -
Understanding 'GenericForeignKey' in Django
In some cases we might want to store generic model object, rather a particular specific model as 'ForeignKey'. Here is the scenario of such kind. Suppose there are models like User, Project, Ticket and TimeLine as below. class Ticket(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Project(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class User(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Timeline(models.Model): involved_object = ***** event_type = models.CharField(max_length=250, default="created") If we want to store the user activities with these models like "created User, created Project, created Task" in a timeline, we have to create all the three models(User, Project, Task) as 'ForeignKey' fields. This is not a good programming practice. To overcome this, Django's content types framework provides a special field type (GenericForeignKey) which allows the relationship to be with any model. Using 'GenericForeignKey': Here is the solution for the above scenario. There are three parts to setting up a GenericForeignKey: Give your model a ForeignKey to ContentType. The usual name for this field is “content_type”. Give your model a field that can store primary key values from the models you’ll be relating to. For … -
Using Unsaved Related Models for Sample Data in Django 1.8
Note: In between the time I originally wrote this post and it getting published, a ticket and pull request were opened in Django to remove allow_unsaved_instance_assignment and move validation to the model save() method, which makes much more sense anyways. There's a chance this will even be backported to Django 1.8. So, if you're using a version of Django that doesn't require this, hopefully you'll never stumble across this post in the first place! If this is still an issue for you, here's the original post: In versions of Django prior to 1.8, it was easy to construct "sample" model data by putting together a collection of related model objects, even if none of those objects was saved to the database. Django 1.8 adds a restriction that prevents this behavior. Errors such as this are generally a sign that you're encountering this issue: ValueError: Cannot assign "...": "MyRelatedModel" instance isn't saved in the database. The justification for this is that, previously, unsaved foreign keys were silently lost previously if they were not saved to the database. Django 1.8 does provide a backwards compatibility flag to allow working around the issue. The workaround, per the Django documentation, is to create a … -
PyCon 2015 Workshop Video: Building SMS Applications with Django
As proud sponsors of PyCon, we hosted a one and a half hour free workshop. We see the workshops as a wonderful opportunity to share some practical, hands-on experience in our area of expertise: building applications in Django. In addition, it’s a way to give back to the open source community. This year, Technical Director Mark Lavin and Developers Caleb Smith and David Ray presented “Building SMS Applications with Django.” In the workshop, they taught the basics of SMS application development using Django and Django-based RapidSMS. Aside from covering the basic anatomy of an SMS-based application, as well as building SMS workflows and testing SMS applications, Mark, David, and Caleb were able to bring their practical experience with Caktus client projects to the table. We’ve used SMS on behalf of international aid organizations and agencies like UNICEF as a cost-effective and pervasive method for conveying urgent information. We’ve built tools to help Libyans register to vote via SMS, deliver critical infant HIV/AIDs results in Zambia and Malawi, and alert humanitarian workers of danger in and around Syria. Interested in SMS applications and Django? Don’t worry. If you missed the original workshop, we have good news: we recorded it. You can … -
Reviews of two recent Django Books
Introduction When I started building sites in Django, I learned the basics from the excellent Django tutorial. But I had to learn by trial and error which approaches to using Django's building blocks worked well and which approaches tended to cause problems later on. I looked for more intermediate-level documentation, but beyond James Bennett's Practical Django Projects and our Karen Tracey's Django 1.1 Testing and Debugging, there wasn't much to be found. Over the years, ever more interesting introductory material has been showing up, including recently our lead technical manager Mark Lavin's Lightweight Django. But more experienced developers are also in luck. Some of the community's most experienced Django developers have recently taken the time to put down their experience in books so that we can all benefit. I've been reading two of those books and I can highly recommend both. Two Scoops of Django I guess Two Scoops of Django, by Daniel Roy Greenfeld and Audrey Roy Greenfeld, isn't that recent; its third edition just came out. It's been updated twice to keep up with changes in Django (the latest edition covers Django 1.8), improve the existing material, and add more information. The subtitle of the most recent edition … -
Django and Python 3 How to Setup pyenv for Multiple Pythons
We need to be doing Django development in Python 3. Unfortunately, we have a lot of projects still in Python 2.7 so switching between the 2 versions can be frustrating. Fortunately pyenv takes the guess work out of switching, and makes it super simple.Watch Now... -
A couple quick tips
As noted yesterday, I’ve spent the last little while working to freshen up various bits of open-source code I maintain, in order to make sure all of them have at least one recent release. Along the way I’ve picked up a few little tips and tricks; some of them may be old hat to you if you’ve been lucky enough to be working with fairly modern Django and Python versions for a while, but I ... Read full entry -
A couple quick tips
As noted the other day, I’ve spent the last little while working to freshen up various bits of open-source code I maintain, in order to make sure all of them have at least one recent release. Along the way I’ve picked up a few little tips and tricks; some of them may be old hat to you if you’ve been lucky enough to be working with fairly modern Django and Python versions for a while ... Read full entry -
Testing Django Views Without Using the Test Client
Testing Django Views Without Using the Test Client -
[Django Tips] Make Django Development Server Persistent.
I use Emacs for writing Python code. I also use real-auto-save to save my files after 10 seconds of inactivity.While coding, when I stop writing in the middle, after 10 seconds Emacs auto saves the file. Django recognizes this & reloads the development server.Once I complete writing code, I go to browser & refresh the page. Since the code I was writing was incomplete somewhere in the middle and had some errors, Django development server was stopped and page won't reload. Now I have to go back to terminal and restart the server and again go back to browser to refresh page.To overcome this, Django server must be made persistent. The easiest way to accomplish this is to use a simple bash script as described here.$ while true; do python manage.py runserver; sleep 4; doneWhen Django development server stops, after 4 seconds it tries to start automatically and goes on forever.Instead of typing that everytime, it better to write this as a shell script and put it in system path, so that it can be used in any project.while true; do echo "Re-starting Django runserver" python manage.py runserver sleep 4doneSave this & make it executable(chmod +x), use it is ./filename.sh and to stop … -
The uWSGI Swiss Army Knife
uWSGI is one of those interesting projects that keeps adding features with every new release without becoming totally bloated, slow, and/or unstable. In this post, we'll look at some of its lesser used features and how you might use them to simplify your Python web service. Let's start by looking at a common Python web project's deployment stack. Nginx: Static file serving, SSL termination, reverse proxy Memcached: Caching Celery: Background task runner Redis or RabbitMQ: Queue for Celery uWSGI: Python WSGI server Five services. That's a lot of machinery to run for a basic site. Let's see how uWSGI can help you simplify things: Static File Serving uWSGI can serve static files quite efficiently. It can even do so without tying up the same worker/thread pool your application uses thanks to it's offloading subsystem. There are a bunch of configuration options around static files, but the common ones we use are: offload-threads the number of threads to dedicate to serving static files check-static this works like Nginx's @tryfiles directive, checking for the existence of a static file before hitting the Python application static-map does the same, but only when a URL pattern is matched Other options exist to allow you …