Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django Conditional Expressions in Queries
Django Conditional Expressions are added in Django 1.8. By using Conditional Expressions we can use "If...Elif...Else" expressions while querying the database. Conditional expressions executes series of conditions while querying the database, It checks the condition for every record of the table in database and returns the matching results. Conditional expressions can be nested and also can be combined. The following are the Conditional Expressions in Django and Consider the below model for sample queries class Employee(models.Model): ACCOUNT_TYPE_CHOICES = ( ("REGULAR", 'Regular'), ("GOLD", 'Gold'), ("PLATINUM", 'Platinum'), ) name = models.CharField(max_length=50) joined_on = models.DateField() salary = models.DecimalField() account_type = models.CharField( max_length=10, choices=ACCOUNT_TYPE_CHOICES, default="REGULAR", ) 1. WHEN A When() object is used as a condition inside the query from django.db.models import When, F, Q >>> When(field_name1_on__gt=date(2014, 1, 1), then="field_name2") # if we want the value in the field >>> When(field_name1_on__gt=date(2014, 1, 1), then=5) # we can specify external value in place of "5" >>> When(Q(name__startswith="John") | Q(name__startswith="Paul"), then="name") # we can also use nested lookups 2.CASE A Case() expression is like the if ... elif ... else statement in Python. It executes the conditions one by one until one of the given conditions are satisfied. If no conditions are satisfied then the … -
Caktus at PyCaribbean
For the first time, Caktus will be gold sponsors at PyCaribbean February 18-19th in Bayamon, Puerto Rico. We’re pleased to announce two speakers from our team. -
Local Domain & Subdomain Testing in Mac & Linux
What to do when you want to te... -
How to Vett Django Apps
There are a lot of 3rd party django apps that people put out which makes our lives easier, but are they good? There are a lot of ways to evaluate them, mostly it seems a lot of people use intuition. In this weeks video I go over several ways of how I go about vetting projects before use in my projects. How to Vett Django Apps -
Asynchronous Tasks Setup using Django, Celery and rabbitMQ
In this post, I’ll be talking about setting up a distributed task processing system for doing asynchronous processing. As your website grows and handles lot of traffic, there naturally comes a need to ensure best performance for your users. While there are multiple things which need to be done to achieve that, one of the most important things is processing things in background. One of the common example is sending an email to the user. Instead of sending the email synchronously and making the user wait till it completes, a better way is to put this email into a queue to be processed in background and let the user continue with other actions. Email is just an example, there are tons of other things which can be moved to background processing to give seamless experience to the user. Also if you are getting too many requests, your server might be busy in processing them one by one and lot of users have to wait for the request to be served if you are doing everything synchronously. The background processing comes as an effective way to solve this. In this post, we will learn to setup this system using Django, Celery, … -
Refactoring Django With Full Syntax Tree
Django developers decided to drop Python 2 compatability in Django 2.0. There are serveral things that should be refactored/removed. For example, in Python 2, programmers has to explicitly specify the class & instance when invoking super. class Foo: def __init__(self): super(Foo, self).__init__() In Python 3, super can be invoked without arguments and it will choose right class & instance automatically. class Foo: def __init__(self): super().__init__() For this refactoring, a simple sed search/replace should suffice. But, there are several hacks in codebase where super calls the grandparent instead of the parent. So, sed won't work in such cases. It is hard to refactor them manually and much harder for reviewers as there are 1364 super calls in code base. → grep -rI "super(" | wc -l 1364 So changes has to be scripted. A simple python script to replace super calls by class names will fail to capture classes with on top of them, classes with decorators and nested classes. To handle all these cases, this python script gets more complicated and there is no guarantee that it can handle all edge cases. So, a better choice is to use syntax trees. Python has ast module to convert code to AST … -
Provisioning django application using ansible
As I recently have opportunity of having a workshop about ansible in my work and I decided to write a blog post on how to provision django application using this tool. In this blog post I am using the same application as in puppet post. Table of Contents: What is ansible and how's is different from puppet Provisioning django application using ansible My thoughts and feelings about ansible What is ansible and how's is different from puppet Ansible is a tool that helps automate boring tasks. These tasks are connected with setting up Linux machines, installing proper software on them and moving code from repositories to machines. Ansible has a different way of accomplishing these tasks than puppet. It is using push system - in short ansible connects to your machine via ssh and push changes. No need for masters and agents etc. Puppet, on the other hand, is using pull system which allows every machine to pull changes from master. Ansible is using the same principles as puppet so you declare how should host look like after running ansible. Provisioning django application using ansible I will be provisioning geodjango-leaflet. I assume that you know basic concepts of ansible like … -
Provisioning django application using ansible
As I recently have opportunity of having a workshop about ansible in my work and I decided to write a blog post on how to provision django application using this tool. In this blog post I am using the same application as in puppet post. Table of Contents: What is … -
Introducing Ask
What is it? A community-pow... -
Introduction to API development using Django REST framework with Example
Django REST framework is a best toolkit to create an API It supports both ORM and Non-ORM data sources. It can support regular function based view and class based views. 1) Installation of Django REST framework. pip install djangorestframework 2) Add 'rest_framework' in 'INSTALLED_APPS' settings.py INSTALLED_APPS = ( ... 'rest_framework', ... ) 3) configure the Django REST framework with 'REST_FRAMEWORK' This framework already contains some default configurations though we can override them like below settings.py REST_FRAMEWORK = { .... 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), .... } Now, we are ready to use the Django REST framework. It is very similar to the Django. Now create your app and add it to INSTALLED_APPS in settings.py. consider the below code for example. we are writing both function and class based views. You can use function based or class based based on your comfort. models.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other') ) class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(unique=True) username = models.CharField(max_length=100, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) dob = models.DateField(null=True) phone = models.CharField(max_length=20, null=True) gender = models.CharField(choices=GENDER_CHOICES, max_length=6) address = models.TextField() password = models.CharField(maxlength=255) def … -
Best free and paid Python Django hosting
Python is a great programming language ,combined with many great tools and frameworks ,it will help you be a very productive developer . Personally i'm using Python for web development with the powerful open source Django framework . Django is a pragmatic web framework for perfectionists with deadlines which can help you build your web project prototype quickly and then build upon it to finish the final project at record time . OK that's cool but how about hosting ? A web project either if it is an ordinary website or a full fledged web application needs web hosting . Many new comers to Django and web developers looking for adopting Django as their web framework ,ask about hosting from the availability of good providers to service costs so in this post i'm going to list some of the best options for hosting Django projects either free and paid ones so I can help you choose the right solution for you but please pay attention . Choosing the right hosting provider depends heavily on your requirements .While many providers provide free Django hosting , you should only use it for testing purposes or for playing with the provider's infrastructure or … -
Django-REST Framework Object Level Permissions and User Level Permissions
Let us cosider the scenario of Authors, Books, Readers. Authors are only allowed to write the books Readers are only allowed to read the Books. models.py from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class User(AbstractBaseUser, PermissionsMixin): USER_TYPES = ( ("Author", "Author"), ("Reader", "Reader"), ("Publisher", "Publisher") ) username = models.CharField(max_length=100, unique=True) first_name = models.CharField(_("first name"), max_length=30, blank=True, null=True) last_name = models.CharField(_("last name"), max_length=30, blank=True, null=True) email = models.EmailField(_("email address"), unique=True) is_staff = models.BooleanField(_("staff status"), default=False) is_active = models.BooleanField(_("active status"), default=True) user_type = models.CharField(choices=USER_TYPES) def __str__(self): return self.email class Book(models.Model): READ_OPTIONS = ( ('YES', 'YES'), ('NO', 'NO') ) name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() is_allowed_to_read = models.CharField(choices=READ_OPTIONS) def __str__(self): return self.name permissions.py from rest_framework.permissions import BasePermission class IsAllowedToWrite(BasePermission): def has_permission(self, request, view): return request.user.user_type == "Author" class IsAllowedToRead(BasePermission): def has_object_permission(self, request, view, obj): return obj.is_allowed_to_read == "YES" views.py from rest_framework import generics from app.permissions import IsAllowedToWrite, IsAllowedToRead from app.serializers import WriteBookSerializer, class WriteBookView(generics.CreateAPIView): serializer_class = WriteBookSerializer permission_classes = (IsAllowedToWrite,) class ReadBookView(generics.RetrieveAPIView): serializer_class = ReadBookSerializer permission_classes = (IsAllowedToWrite,) Find our Django REST Framework … -
How to fix Django’s HTTPS redirects in nginx
You deploy with nginx and Gunicorn and your site uses HTTPS. If Django occasionally returns HttpResponseRedirect or similar, you may find that the redirect sends you back to HTTP. Here’s how to fix it. In the nginx configuration (inside the location block), specify this: proxy_redirect off; proxy_set_header X-Forwarded-Proto $scheme; The proxy_redirect off statement tells nginx that, if the backend returns an HTTP redirect, it should leave it as is. By default, nginx assumes the backend is stupid and tries to fix the response; if, for example, the backend returns an HTTP redirect that says “redirect to http://localhost:8000/somewhere”, nginx replaces it with something similar to “http://yourowndomain.com/somewhere”. But Django isn’t stupid (or it can be configured to not be stupid), and it will typically return a relative URL. If nginx attempts to “fix” the relative URL, it will likely break things. Instead, we use proxy_redirect off so that nginx merely passes the redirection as is. The second line is only necessary if your Django project ever uses request.is_secure() or similar. It’s a good idea to have it because even if it doesn’t today it will tomorrow, and it does no harm. Django does not know whether the request has been made through … -
Install Django on Mac
#### Install Django & Virtuale... -
Install Python & Django on Windows
### Install Python & Django on... -
Common Regular Expressions for Django URLs
Common Regular Expressions for... -
Python Cheat Sheet
A quick reference guide for us... -
My Equipment
### Computer Laptop: [http:... -
AngularJS vs jQuery
### AngularJS is a framework ... -
Django App Structure
To make your individual Django... -
Syncdb is ... gone?
Yup `python manage.py syncdb` ... -
A Fantastic Ted Talk
This is by far one of the most... -
Everything coming in 2017
Topics</... -
*args and **kwargs
So when you write any given fu... -
Testing Email in Django with send_mail
Sometimes you need to test tha...