Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Getting Started with Django Admin
The admin is a very useful tool for developers to use when working with django. It is super easy to setup, and get your models registered with it so you can start CRUDing data.Watch Now... -
Making Clean Code a Part of Your Build Process (And More!)
At Caktus, “clean” (in addition to “working”!) code is an important part of our delivery. For all new projects, we achieve that by using flake8. flake8 is a wrapper around several tools: pep8, pyflakes, and McCabe. pep8 checks to make sure your code matches the PEP 0008 style guidelines, pyflakes looks for a few additional things like unused imports or variables, and McCabe raises warnings about overly complex sections of code. -
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. -
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 and funding 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. -
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. -
[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 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 … -
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 … -
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. It's likely this will even be backported to Django 1.8.4. 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: -
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. -
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. -
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... -
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 … -
Django Tips & Tricks #4 - 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 … -
Understanding Django Middlewares
I assume you have read official Django docs on middleware. I will elaborate on things mentioned in the documentation but I assume you are familiar with basics of middleware. In this post we will discuss the following. What is a middleware When to use middleware Things to remember when writing middleware Writing some middlewares to understand how order of middleware matters What is a middleware Middlewares are hooks to modify Django request or response object. Putting the definition of middleware from Django docs. Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output. When to use middleware You can use middleware if you want to modify the request i.e HttpRequest object which is sent to the view. Or you might want to modify the HttpResponse object returned from the view. Both these can be achieved by using a middleware. You might want to perform an operation before the view executes. In such case you would use a middleware. Django provides some default middleware. eg: AuthenticationMiddleware Very often you would have used request.user inside the view. Django wants user attribute to be set on request before any view …