background preloader

Tango with Django

Tango with Django
Related:  Django

Cheat Sheet The django tutorials are quite good. The goal of this cheat sheet is to create a quick start guide so that after reading the tuts over once or twice you have a more handy reference. Things in this guide are done the 'right' way with generic views and templates right off the bat. (It would be great if some of the stuff from this page could later be rolled in to the startproject command and handled automatically - SimonWillison) startproject AcmeIntranet cd AcmeIntranet mkdir templates mkdir media edit your database settings set path to media dir ( e.g. python syncdb python startapp invoices add 'AcmeIntranet.invoices', to INSTALLED_APPS list in Create your data model ¶ see: ​model api, ​model examples add your app to INSTALLED_APPS in validate your model and commit to database: python validate python sql invoices python syncdb Design your urls ¶ in the project root directory, edit <!

Test-Driven Development with Python Test-Driven Development with Python Test-Driven Development with Python Harry Percival Gillian McGarvey Rebecca Demarest Wendy Catalano Randy Comer David Futato Copyright © 2014 Harry Percival Printed in the United States of America. O’Reilly books may be purchased for educational, business, or sales promotional use. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. Praise for Test-Driven Development with Python Table of Contents © 2013, O’Reilly Media, Inc.

Regular Expressions This quick start gets you up to speed quickly with regular expressions. Obviously, this brief introduction cannot explain everything there is to know about regular expressions. For detailed information, consult the regular expressions tutorial. Each topic in the quick start corresponds with a topic in the tutorial, so you can easily go back and forth between the two. Many applications and programming languages have their own implementation of regular expressions, often with slight and sometimes with significant differences from other implementations. Text Patterns and Matches A regular expression, or regex for short, is a pattern describing a certain amount of text. Characters with special meanings in regular expressions are highlighted in various different colors. Literal Characters The most basic regular expression consists of a single literal character, such as a. This regex can match the second a too. Learn more about literal characters Character Classes or Character Sets Anchors q(? q(?!

So You’d Like To Make a Map Using Python Making thematic maps has traditionally been the preserve of a ‘proper’ GIS, such as ArcGIS or QGIS. While these tools make it easy to work with shapefiles, and expose a range of common everyday GIS operations, they aren’t particularly well-suited to exploratory data analysis. In short, if you need to obtain, reshape, and otherwise wrangle data before you use it to make a map, it’s easier to use a data analysis tool (such as Pandas), and couple it to a plotting library. PandasMatplotlibThe matplotlib Basemap toolkit, for plotting 2D data on mapsFiona, a Python interface to OGRShapely, for analyzing and manipulating planar geometric objectsDescartes, which turns said geometric objects into matplotlib “patches”PySAL, a spatial analysis library Package installation This tutorial uses Python 2.7.x, and the following non-stdlib packages are required: IPythonPandasNumpyMatplotlibBasemapShapelyFionaDescartesPySAL Running the Code Some (16, to be exact) of my lines are over-long. Obtaining a basemap

get_context_data alternative Tags: django There’s a super nice super elegant productivity trick for Django class based views. Something that is not very well know, as I discovered at last week’s djangocon. The problem? def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(PublisherDetailView, self).get_context_data(**kwargs) # Add in a QuerySet of all the books context['book_list'] = Book.objects.all() return context In the template you’d use it like this: {% for book in book_list %} ... {% endfor %} The solution? from django.views.generic import TemplateView class SomethingView(TemplateView): template_name = "something.html" title = "My beautiful list of books" def books(self): return Book.objects.all() # Note: no get_context_data() here! The template then uses the automatic view variable to grab the list of books and the title: <h1>{{ view.title }}</h1><ul> {% for book in view.books %} <li>{{ book }}</li> {% enfor %} <ul> Isn’t that wonderful? Some notes:

Python List Examples – Insert, Append, Length, Index, Remove, Pop Lists in Python language can be compared to arrays in Java but they are different in many other aspects. Lists are used in almost every program written in Python. In this tutorial we will understand Python lists through practical examples. We will cover the following in this article : How to define a listHow to add elements to a listHow access sub listsHow to search within listsHow to delete elements from a listOperators and lists 1. Defining a List in Python is easy. >>> myList = ["The", "earth", "revolves", "around", "sun"] >>> myList ['The', 'earth', 'revolves', 'around', 'sun'] So you can see that a list named ‘myList’ was created with some elements. Lists in python are zero indexed. >>> myList[0] 'The' >>> myList[4] 'sun' Lists cannot be accessed beyond the rightmost index boundary. >>> myList[5] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range >>> myList[-1] 'sun' 2. So, the two values were appended towards the end of the list.

The step-by-step tutorial I wish I had when learning Ajax in Django (with JQuery) — Part one of three | aliteralmind — Computer Programming Blog This tutorial demonstrates implementing Ajax in Django, using JQuery, for two specific tasks: A search box that executes on each key press.A like button that says "yes" if it’s liked, and "no" if it’s not. Take a look at a mockup of the website we’re going to be creating, which is written in Knockout. In addition, we’ll add in some basic protection against rapid-fire requests, by preventing the search form from submitting until at least two characters are provided, and by ignoring clicks of the same like-button if it is pressed again within a half-second. First we’ll create the website without Ajax, and then we’ll integrate the Ajax calls. Before going through this tutorial, you’ll need a basic understanding of both Django (and Python!) This is how I learned Django. I learned Python by reading the official tutorial and Dive Into Python 3, running through the Coding Bat and codecademy tutorials, and especially by immersing myself in Django. Now… and then sync it to the database: Like this:

Python Dictionary Examples – Create, Update and Delete Elements Dictionary in python consists of keys and their values. This article is part of our ongoing series on python. In the first article of the series, we explained how to use variables, strings and functions in python. In this tutorial, we’ll understand the basics of python dictionaries with examples. 1. Here is an example of how we can create a dictionary in Python : In the above example: A dictionary is created.This dictionary contains three elements.Each element constitutes of a key value pair.This dictionary can be accessed using the variable myDict. 2. Once a dictionary is created, you can access it using the variable to which it is assigned during creation. Here is how this can be done : >>> myDict["A"] 'Apple' >>> myDict["B"] 'Boy' >>> myDict["C"] 'Cat' So you can see that using the variable myDict and Key as index, the value of corresponding key can be accessed. If you just type the name of the variable myDict, all the key value pairs in the dictionary will be printed. 3. 4. 1. 2.

High Performance Django The Book Python Introduction Tutorial – Variable, String, Function Examples Python is an object oriented language with can be used in both scripting and non scripting contexts. Python has clean and easy syntax that makes it easy to read. In this article, we will understand python language from scratch through examples. We will often compare Python programming features/syntax with some popular languages like C/C++. Also, we will be using Linux command line for all the examples. This is a new series. 1. Here is the simple “Hello World” example in python: $ vi print "Hello World" Note that the ‘print’ in python does not require parenthesis. Now run the above python program on command line in the following way : $ python Here is the output : Hello World So we see that the single ‘print’ statement executed and the string “Hello World” was displayed in output. Now lets try adding another ‘print’ statement to the python script example: $ cat print "Hello World" print "This is my first python program" 2. myIntVar = 5 3. 4.

Getting Started with Django Logging in 5 Minutes Getting Started with Django Logging in 5 Minutes posted by Ian on April 16, 2013 Setting up Django logging can sometimes be a little complex, so here are the no-nonsense steps required to make a new Django 1.5 instance log to a file without hassles. Loggers: a logger is the object that we will use to pass messages to the logging systemHandlers: the handler is an engine that determines what to do with a message when it is recieved from the loggerFilters: allow you to restrict the type of messages that are sent from the logger to the handlerFormatters: describe the text representation of the log message Simple, right? Setting up your Project for Logging Logging configuration is specified in your project’s file. Formatters First let’s declare the format that we can log entries in. Filters In my example, I don’t want to filter anything. This defines one filter, project.logging.SpecialFilter, using the alias special. Handlers This is where it gets fun. Loggers Full Project Configuration

Obey the Testing Goat! Someone recently wrote to me asking about decorators, and saying they found them a bit confusing. Here's a post based on the email I replied to them with. The best way to understand decorators is to build a couple of them, so here are two examples for you to try out. The first is in the Django world, the second is actually a simpler, pure-python one. Challenge: build a decorator in a simple Django app We've built a very basic todo lists app using Django. (Full code here) This is a good use case for a decorator. A decorator can be used to extract duplicated work, and also to change the arguments to a function. So how do we build a decorator that does that? (you end up saying "function" a lot in any explanation of decorators...) Here's a template: def get_list(view_fn): def decorated_view(...?) Can you get it working? git clone -b chapter_06 test lists # dependencies: django 1.7 Some rules of thumb for decorators: A simpler decorator challenge:

VirtualEnvForNewerDjango - PythonAnywhere A virtualenv is a way to have your own private Python environment that has different versions of packages to the system default. You can have many virtualenvs, each with its own versions of installed packages. On PythonAnywhere, this is a great way to use newer (or older) versions of software than the ones we have installed. One reason you might want to do this is to use a newer version of Django. For Python 2.7, our system default is currently 1.3.7, while the latest version is 1.7. These instructions explain what to do if you want to use Django 1.7; if it's a different package that you want to upgrade (or you need a different version of Django), then the changes should be pretty obvious. Instructions Log in to PythonAnywhere, and create a new Web app: Go to the "Web" tab. Now you can check that you have a web app -- go to in your browser to see the simple site we generate for you. Next, we need to create the virtualenv. workon django17 Now install Django: And