Introduction to Python and Django for Web Development
If you are interested in web development, you would definitely find Django interesting. Django is essentially a web development framework based on Python. It has been designed to save you lots of time and make web development much simpler and more fun. You can use Django to build and maintain high-quality web applications without much fuss.
Web development in itself is a mix of creativity and fun elements, and a bunch of repetitive stuff. What Django does is it lets you focus on the fun bits and the key part of your web application, while making the repetitive parts less of a hassle. In other words, it provides a shortcut to frequent programming tasks and abstractions of common patterns in web development. It also gives clear conventions on problem-solving. It does all this while also giving you the freedom to work outside the framework scope when needed.
What Is a Web Framework?
Of course, before we introduce Django, we need to first know what web frameworks are, given their importance in today’s web applications. To understand web frameworks, let’s take a look at how a Python application is coding when you don’t use a framework. The simplest way to do this is with a Common Gateway Interface (CGI). You just need to create a script with an HTML output, and then save the script with a. cgi extension to a web server. For simple pages, a write-from-scratch approach is probably best. The code is simpler to understand, and there is no other code to read. It is also simpler to deploy.
Despite its simplicity, the approach comes with several challenges. For example, what would you do if you needed multiple parts of your application to connect to a database? If you go by the above method, you would have to duplicate the database connecting code in each CGI script. This can not only be cumbersome, it can also increase the chances of human error creeping in. The easier method, however, would be to put this code in a shared function. When the code is reused in various environments with a separate password and database, you will have to configure the code for each specific environment.
Also, if you don’t have much experience with Python, you are more likely to make smaller errors that can cause the application to crash. The logic of the page would ideally separate from the HTML display elements, so the editor could edit each element without affecting the other.
A web framework resolves these issues by forming an infrastructure to program applications. This helps you focus on actually writing more maintainable and cleaner code. This is also what Django does.
Django closely follows the Model-View-Controller (MVC) pattern, so much so that it could just about be categorized as an MVC framework. This pattern separates the domain modelling, presentations and user input-based action into three unique classes. To understand this better, just take a look at a Python CGI script.
A standard CGI script will include some introductory HTML elements for the front end and then a connection to a database. Here is an example code of a database connection in a Python CGI:
connection = MySQLdb.connect(user='ABC', passwd='xxxxxxxx', db='my_db')
After that, you have an execution command for running the query. You then have some HTML to display the results of the query in the front-end. Finally, you close the connection with a simple line:
Now, with Django, you have three Python files, identified with their. py suffix. The first would be the database tables, models.py. The second would contain the application logic, views.py. And the third would have the URL configuration, urls.py. Finally, you would have some HTML elements to present the results at the front-end. The separation on various Python files is the key here; you don’t have to worry about the syntax.
The models.py file has a description of the database table. Using this Python class, you can create, delete, retrieve and update records using simple Python code instead of repeating SQL statements. The views.py file has the business logic, and the latest_books() function is the view. The urls.py file specifies what view is called for a given URL. For instance, you could code a view to be called for in case the browser loads a domain URL /example/. This means that if your domain is abc.com, a visit to the URL abc.com/example/ would call this function.
The HTML template describes the page design. It uses a template language and basic logic statements. Altogether, these pieces follow the MVC pattern.
MVC is a method of software development in that the model, which is the code for accessing and defining data, is separate from the controller, which is the request-routing logic, which is also separate from view, which is the user interface. MVC is useful in that the components are very loosely coupled. Each part of the web application thus has its own single purposes and can be independently changed without having to change other pieces drastically. For instance, you can change the URL at any part of the application and it would change the implementation, and without touching the Python code rendering it. You can rename a table in the database and specify changes in a single place without replacing dozens of files.
A brief history of Django
Now that you know a little about web frameworks, it is time to dig a little into the history of Django. Knowing where Django comes from can help you better understand how it works and how to operate its shortcuts. If you have been building web applications, you would probably already know the problems associated with CGI. The classic path of web development goes like so:
- You write a web application from ground up
- You write a second application
- You realize that there are several common elements between the two applications
- You refactor the code so that application 1 has the same code as the second one
- You repeat 2-4 a few times
- You realize that you’ve formed a framework
This is how Django was created too. It was formed from real-world applications that were written by a web development team in Kansas. It was created in 2003, when web programmers Adrian Holovaty and Simon Willison started using Python for building applications.
The World Online team, responsible for maintaining and producing several local news sites, saw huge benefits in a web development environment that was dictated by the deadlines of journalism. For the sites, the journalists and management wanted features to be added and applications to be built on a fast schedule, with just days or hours of notice. The two developers then formed a web development framework for saving time and building maintainable applications within the deadlines.
The team then released the framework as an open source software in the summer of 2005, naming it Django after Django Reinhardt, arguably one of the greatest jazz guitarists of all time. Since then, Django has established itself as a popular open source project with thousands of supporters, contributors and users worldwide. Two of the original developers, Jacob and Adrian, still given their central guidance for the growth of the framework.
But why are we even discussing the history of Django? Well, for two reasons. The first is that it helps identify and explain the ‘sweet spot’ of the software. Django was borne out of a news environment and is therefore full of features best suited for content-focused sites, like the Washington Post, Amazon and Craigslist, offering database-driven and dynamic information. Still, Django is also good for any dyamic website. The second reason is that Django’s history helps you understand how its community’s culture has been shaped.
Django has been formed from real-world code and not from a commercial product or academic exercise. As a result, it is highly focused on solving problems faced by the original web developers, and problems that current developers still face. This means that Django sees almost daily improvements. The framework maintenance crew has a vested interest to make sure that the tool saves time for the developer and produced easily maintained applications, and ones that perform well in heavy loads. They all want to make things easier for themselves, in other words.
So, it should be pretty clear by now that Django is a tool for simplifying web development. But installing the tool itself can take a few steps due to the number of moving parts in today’s web development environments.
Django is basically Python code, so it runs anywhere that Python does, which includes some cellphones too. Let’s assume that you are installing it on a desktop or laptop, or a server. Since Django is written in Python, you first need Python installed. The core Django frameworks with any Python version from 2.5 onwards. If you are not sure what to choose, pick the latest version of Python since they have language features and performance improvements you might find useful.
If you are on Mac or Linux, you probably already have Python in your computer. You can verify this by going to command prompt and typing ‘python’ at the command line. You should see something like this:
Python 3.5.1 (v3.5.1: 37a07cee5969, Dec 6 2015, 01:54:25)
[MSC v.1900 64 bit (AMD64)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.
If you don’t see this, you need to download and install it. Once installed, you have to download and install Django. You can chose from two versions: the latest official release or the bleeding-edge web development release. What you choose is based on what you want. If you want a tested, stable version, go for the official release. If you want something with the latest features and want to contribute to the community, and can handle the lack of stability, go for the web development version.
To begin with, it’s best to go for the official release. You can find the latest one on the Django Project website. If you have a Linux distribution with Django package, go for the distributor’s version so that you get security updates too.
Setting Up a Database
Django’s only prerequisite is that you have a working Python installation. Once you have that set up, you can pretty much start writing a web application right away. However, as mentioned before, Django was developed with a focus on content-focused, database-driven web applications. So the odds are you will develop a database-driven website. In that case, you need to set up a database server.
Django supports four database engines: MySQL, Oracle, SQLite 3 and PostgreSQL. All the engines work equally well for the most part with the core framework. PostgreSQL is recommended if you do not have ties to a legacy system and can choose a database backend.
To set up a database, you need to install and configure the server itself. Each database you choose has its own way of setting up, so you need to refer to that. Secondly, you have to install the Python library for that particular database backend. This is third-party code for Python to interface with the database.
SQLite is recommended if you are just experimenting with Django and do not want to install a server. It does not require installation; it can just read and write data to a single file on your system, and it is supported by Python 2.5 and higher. Windows makes it a bit difficult to obtain database driver binaries.
If you opt for MySQL, you need MySQL 4.0 or higher since the older versions do not support Django’s features. You also have to install the MySQLdb package from the Django Project page. If you are using Linux, your distribution’s package management system may have a package called ‘mysql-python’, ‘python-mysqldb’ or ‘python-mysql’.
Django works with versions 9i or higher of the Oracle Database Server. You also need to install the cx_Oracle library from the cx-Oracle website. Alternatively, you can use Django without a database entirely, if you want to only use it to serve dynamic pages without referencing a database. With that said, some of the tools in Django do require a database, and not having one will cause you to miss out on them.
Here are some articles that will help you to get more detail about the Python and Django for Web Development so just go through the link.