Below you will find pages that utilize the taxonomy term “Python”
Django and NGINX in Docker
In this post we will run Django application behind a NGINX webserver, which is a very common practice in production.
Django CRUD (Create, Retrieve, Update, Delete)
One of the most common task when developing web application is to write create, read, update and delete functionality (CRUD) for each table you have.
In this post I briefly cover the step needed to create a CRUD app in Django, the steps we will need are:
Django with Docker: Add Postgres
In the last post I covered starting a new Django project with Docker, and how to build a custom container image for my project, but what I haven’t covered is how to use a Database and how persist your data since all data stored in the container ephemeral and would only exist during the life span of the container.
Django with Docker: Build an Image
Docker is an interesting technology, although still young it gained a lot of buzz and momentum.
The last couple of weeks I started playing with Docker to see how can I use it for Django project development and deployment.
Django: How to pass an url as parameter of include
In Django web applications I usually have a single template file for navigation or bread crumb that I include from other template files, it is easy and straight forward to pass parameter to the included template file, some thing like:
{% include "nav.html" with title="title" object=my_object %}
But it would be a little tricker to send a URL as a parameter, i.e. you can’t write it:
{# WRONG DOESN'T WORK #}
{% include "nav.html" with title="title" link={% url 'book_edit'%} %}
But luckily Django have a decent and elegant solution, you can use “url” template function with “as” parameter, which will not display but will store it in a variable that you can use later in the include function:
My first public Python Package “pyagentx”
I’ve just published my first public Python package “pyagentx”, the package will help you build “AgentX” agents to extend a master SNMP agent.
Let’s assume that you want to monitor your custom application from your Network Managment System (NMS), but the NMS only speak SNMP, this package allows you to extend the master SNMP agent to include your custom application metrics.
Django Image and File Field Caveats
Every time I work with Image or File fields in Django I forget some tiny detail that waste 10-20 minutes until I remember what was I missing, I always say I will remember it next time but I never do! so I made a list of common errors I keep doing while working with Image/File fields:
For complete working project: (https://github.com/rayed/dj-imagefield-example)
Setting MEDIA_URL and MEDIA_ROOT
Make sure you set proper values for MEDIA_URL and MEDIA_ROOT in your settings.py, e.g. I use the following structure:
Install psycopg2 (PostgreSQL adapter for Python) on OSX
I was playing with Django with Postgres backend, and I had little difficulty installing “psycopg2” the Python DB adapter for Postgres on my Mac OSX.
I’ve installed Postgres using Postgres.app for OSX which is straight forward and standard Mac app.
But when I tried installing “psycopg2” using “pip” (the python package manager) I got an error:
$ pip install psycopg2
:
Error: pg_config executable not found.
:
I just searched for “pg_config” in my system:
Solving Python virtualenv “DistributionNotFound: distribute”
After upgrading my Ubuntu machine from 12.04 to 14.04 I had this error on virtualenv wrapper:
Django Themes (or where to put base.html?)
The Wrong Way
I used to create a new directory to hold common templates like “base.html”, and add it TEMPLATES_DIR in the settings.py file:
Django returning JSON for AJAX requests
In your views.py
you can have a page that return JSON data for AJAX request like this:
Setting Up Python and Supervisor on CentOS
CentOS default repository is very limited, and even if you install EPEL you will get old packages, in my case I needed to install Supervisor to manage my Django application, after trying to do it manually and through EPEL I ended up with the following setup.
Django Multiple Settings with Single File
Instead of having multiple settings files one for production and one for development and so on, I prefer to use an “if” statement with environment variable:
Django “render” vs “render_to_response”
Summary: Always use render
and not render_to_response
In Django you have more than one way to return a response, but many times I get confused between render
and render_to_response
, render_to_response seems shorter, so why not use it!
Install Python Image Library (PIL) on OSX
PIL or Python Imaging Library is a library that allows you to manipulate images in Python programming language, trying to install “PIL” using “pip” tool won’t work perfectly so here is how to proper installation.
My New Project: AgentX Implementation in Python
During this Eid vacation I spent many hours working on AgentX implementation in Python.
You can find the project in GitHub:
Python auto complete in OSX
If you run Python shell in OSX you notice the auto completion functionality isn’t working, this is caused by Apple decision not to ship GNU readline and instead they use libedit (BSD license), to fix the problem I used the following snippet:
IPython Import Error
I tried to install IPython to play with it and learn more about scientific Python packages, but I faced an error on my first step:
Implementing Login/Logout in Django
Update: add names and namespace to URLs
Implementing user authentication is fairly easy job in Django, many functionalities are already included in the standard Django installation, you can manage users using the default “admin” app the comes with Django.
Here I will show how implement Login/Logout feature by relying on Django built-in views.
Django Serving Static Files without a Web Server
UPDATE: Steps in this post isn’t correct, check the Django Themes post for better solution.
When deploying Django site it is always recommended to serve static files (e.g. js, css, img, static, media) using a normal web server instead of relying on Django built development server or Gunicorn.
But sometimes you want to test something quick and you don’t want to bother with installing or configuring a web server, the solution is to use the built-in django.views.static.serve view to serve the static files from Django it self:
Managing Python Environments with “virtualenvwrapper”
What is virtualenvwrapper
virtualenvwrapper is a tool that (as the name suggest) wrap “virtualenv” program, virtualenv solve the following problem:
Minimal Django Project: Part 2 … Flat Pages
In this step we will setup the Flatpage App, Flatpage allows you to create simple static pages from the Admin interface:
**mycms$ mkdir templates**
**mycms$ vi mycms/settings.py**
:
MIDDLEWARE_CLASSES = (
:
# Add Flatpage Middleware
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
:
TEMPLATE_DIRS = (
:
'/Users/rayed/python/mycms/templates',
)
:
INSTALLED_APPS = (
:
# Add Flat Pages App
'django.contrib.flatpages',
:
)
:
**mycms$ vi mycms/urls.py**
:
# Your other patterns here
# SHOULD BE THE LAST RULE
urlpatterns += patterns('django.contrib.flatpages.views',
(r'^(?P<url>.*)$', 'flatpage'),
)
**mycms$ ./manage.py syncdb**
**mycms$ mkdir -p templates/flatpages**
**mycms$ vi templates/flatpages/default.html**
<!DOCTYPE html>
<html>
<head>
<title>{{ flatpage.title }}</title>
</head>
<body>
<h1>{{ flatpage.title }}</h1>
{{ flatpage.content }}
</body>
</html>
Now from the admin interface add a new page from “Flat pages” app, and you can view directly from the normal site.
Minimal Django Project: Part 1 … First Run
Update: Django 1.6+ don’t need any of these steps! it will work out of the box.
The following is the shortest way to create DB backed Django project, it uses SQLite as a backend, which make the setup very easy and fast.
I usually use for testing new Django modules or apps.
**$ django-admin.py startproject mycms**
**$ cd mycms**
**mycms$ chmod +x manage.py **
**mycms$ vi mycms/settings.py **
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': './mycms.db',
:
}
}
:
TIME_ZONE = 'Asia/Riyadh'
:
TEMPLATE_DIRS = (
PROJECT_ROOT + '/templates',
)
INSTALLED_APPS = (
:
'django.contrib.admin',
:
)
:
**mycms$ vi mycms/urls.py **
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
:
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
**mycms$ ./manage.py syncdb**
:
provide username, email, password for admin
:
**mycms$ ./manage.py runserver**
:
To access it from outside
:
**mycms$ ./manage.py runserver 0.0.0.0:8080**
To access it: Frontpage @ localhost Admin @ localhost
My Python and Django bookmarks
This a list of Django and Python websites I found useful, I hope you find it useful as well, and may be add to it in the comments:
- Django | Django documentation | Django documentation
- The Django Book
- Django Packages : Django Packages reusable apps, sites and tools directory
- 170+ Django conference videos | Equally True
- ubernostrum / django-registration — Bitbucket
- GoDjango.com – Going Through Django Screencasts
- Sourcefabric | Django Software Stack
- Drupal or Django? A Guide for Decision Makers | scot hacker's foobar blog
- <a HREF=“http://celeryproject.org/" “1335735065” >Homepage | Celery: Distributed Task Queue
- Haystack – Search for Django
- Ginger Tech Stack | Blog | Django Development | Lincoln Loop
- Django Best Practices — Django Best Practices
- 33 projects that make developing django apps awesome — elweb
- Brandon Konkle
- Django Advice / Steve Losh
- Auth tips and tricks
Deploying Django
Django is a web framework written in Python language, my favourite computer programming language.
Python a language is really great language, easy to read and understand, and very easy to learn, but for me I always found setting up Python for web development as a challenge, socially if compare it to PHP, which almost works out of the box, actually most people think PHP works only in the web server and can’t work as stand alone application, search for PHP CLI if you are interested.
I will try here to document an easy Django deployment for my future reference and hopefully it will help others:
Faster file syncing with Redis
The problem
In alriyadh.com most of the site administration take place inside the premises of Alriyadh Newspaper offices, and as you can image the bandwidth dedicated to the website team isn’t that big. This why we designed our system to have two parts, one inside Alriyadh Newspaper internal data center where the local access is very fast, and another part accessible to the public hosted in MeduNet, and we would have a database replication for the website data, and file system replication for the web site images and media.
Django 1.0 released!
Django team released version 1.0 of the their web application framework, Django is written in Python.
I only tried Django for a week more than one year ago, and it was really amazing, and easy to create web application.
Even if you don’t write in Python I recommend you spend sometime to know it, may be walk through the tutorial. It has many inspiring and brilliant features you definitely need to know before select your next web framework.