Python from Scratch—Create a Dynamic Website

So, how do you get started creating websites with Python? Well, you could do it all yourself, and write a program that runs on a web server, accepting page requests and serving up responses in the form of HTML and other resources. However, that’s a lot of work, so why go to all the trouble when there are plenty of existing tools out there to do the job for you? These tools are called frameworks, and they’re what we’ll use today to create our website.

Python Frameworks

There are quite a few Python web frameworks, but here are some of the best:

  • Django: We’re going to use this today. It has a huge set of features, but remains simple to use. The documentation is also excellent, so if you get stuck, you’ll have the easiest time solving your problem with Django.
  • Flask: Flask is a lightweight web application micro-framework designed to be easy to get started due to the many extensions that make adding new functionality easy.
  • FastAPI: FastAPI  is a modern  high-performance web framework for building APIs with Python 3.6+. It is also easy to use and offers autocompletion and linting, making writing code faster than other frameworks.
  • Falcon: Falcon is a minimalist web framework for building fast web APIs and app back-ends.  Falcon offers a clean design that uses HTTP and the REST architectural style for building API’s quickly.

A more comprehensive list can be found on the Python website if you’re in need of additional options. Today we’re going to set Django up for development on a local machine, and then build a simple blog. We’re also going to review the process of installing it on a remote web server.

Installing Django

We’ll be performing most of our work today in the terminal. This should all work on Mac and Linux; however, if you’re running Windows, the process is somewhat different. A familiarity with the command line isn’t necessary if you’re only writing Python, though, if you’re planning on using Django, or running a dynamic website in general, it’s worth learning.

Terminal Tutorials

Consider reviewing these tutorials to get yourself up and running with the Terminal.

Here are the commands you need to install Django. You’ll need to install version Python 3  to get it running.  First you need to create a virtual environment with the venv module. From the Python docs,

The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages in its site directories.

Create a project Directory and a virtual environment inside the project directory

Activate the virtual environment and create a new Django project.

The project directory looks like this:

Django project directoryDjango project directoryDjango project directory

What do each of these files do?

  • __init__.py tells Python that this folder is a Python package. We learned about these in the third lesson; it allows Python to import all of the scripts in the folder as modules.
  • manage.py isn’t actually part of your website; it’s a utility script that you run from the command line. It contains an array of functions for managing your site.
  • settings.py contains your website’s settings. Django doesn’t use XML files for configuration; everything is Python. This file is simply a number of variables that define the setting for your site.
  • urls.py is the file that maps URLs to pages. For example, it could map yourwebsite.com/about to an About Us page.

Django refers to itself an MTV framework, which stands for Model Template View.

Apps

However none of these files on their own make a functional website. For that, we need Apps. Apps are where you write the code that makes your website function, but before we take a look at them, we need to understand a bit about Django’s design principles.

First, Django is an MVC framework, which stands for Model View Controller. Django refers to itself an MTV framework, which stands for Model Template View. It’s a slightly different approach than MVC, but fundamentally, they’re quite similar. Anyhow, MVC is an architectural pattern that provides a method for structuring your projects. It separates the code that’s used to process data from the code that manages the user interface.

Django subscribes to the DRY, or “Don’t Repeat Yourself” philosophy.

Secondly, Django subscribes to the DRY, or Don’t Repeat Yourself philosophy, which means that you should never be writing code that performs a certain task more than once. For example, in our blog, if we wrote a feature that picked a random article from the archive, and implemented this feature on multiple pages, we wouldn’t code it again each time it was needed. We’d code it once and then use it on each page.

So how does this relate to apps? Well, apps allow you to write your website in a DRY style. Each project, like the one we have here, can contain multiple apps. Conversely, each app can be part of multiple projects. Using the example from earlier, this means that if we made another site in the future that also needed a random page feature, we wouldn’t have to write it all over again. We could simply import the app from this project. Because of this, it’s important that each app serves one distinct purpose. If you write all the functionality of your site within one app, and then need to use part of it again later, you have to import it all. If you were making an eCommerce website, for example, you wouldn’t want to import all the blog features. However, if you make one app for the random feature and one app for the blog publishing system, you could pick and choose the bits that you require.

This also means that within the site, the code is well organized. If you want to alter a feature, you don’t have to search through one massive file; you can instead browse to the relevant app and change it without worrying about interfering with anything else.

The directory structure now looks like this:

Django projectDjango projectDjango project

Again, we’ve got an __init__.py file to make it a package, and three other files: models, tests and views. We don’t need to worry about tests for now, but the other two are important. Models and Views are the M and V parts of MVC.

In models, we define our data structures.

If you’ve ever worked with PHP before, you might have used PhpMyAdmin to create your MySQL tables, and then written out your SQL queries manually in your PHP scripts. In Django, it’s much easier. We define all the data structures we need in this models file, then run a command and all the necessary databases are made for us.

When you wish to access that data, you go via these models by calling method on them, instead of running raw queries. This is very helpful, because Django can use several database programs. We’re going to use MySQL today, because it’s the most powerful, and is what most hosts provide, but if we needed to switch to a different database in the future, all of the code will still be valid! In other languages, if you wanted to switch to SQLite or something similar, you would need to rewrite the code that accesses your database.

In the views file, we write the code that actually generates the web pages. This ties all the other parts together. When a user types in a URL, it is sent by the urls script we saw earlier to the views script, which then gets relevant data from the models, processes it and passes it into a template, which finally gets served up as the page the user sees. We’ll take a look at those templates shortly. They’re the easiest part – mostly HTML.

Add the blog app to the list of INSTALLED_APPS in the settings.py file.

For a blog, we’ll need a table of posts, with several fields for the title, body text, author, the time it was written, and so on. A real blog would have comments, but that’s beyond the scope of today’s demo.

MySQL

These models are just a description. We need to make an actual database from them. First, however, we need MySQL running on our system. On an actual web server, this wouldn’t be a problem, because they usually have it preinstalled. 

To install MySQL type:

To check if the installation is successful, use:

This should return something like this:

Now create a MySQL database for the Django project. Run MySQL with sudo mysql and at the prompt enter:

Start the Development Server

You can now run python3.8 manange.py runserver in a new tab to start the development server.

But first we need to  configure the database settings. Let’s take a look at settings.py.

You need to change the database settings first.

Now run the server and go to 127.0.0.1:8000 in your web browser. You should see the default Django page.

default Django page.default Django page.default Django page.

Configure the Blog in Django

Now let’s turn our Django site into a blog. First, we need to use our models to create tables in the database by creating the following migration to effect changes made to the models.

Now run the migration to create tables in the database.

Create a Superuser

Now you can create a superuser to administer your Django app.

Set up the App URLs

Now let’s set up the URLs for the app in the urls.py file. We’ll include the blog URLs as from a separate file.

Create a First View

Let’s create our first view, which will render a simple HTML page. Open blog/views.py and add the following code.

Create the View Template

This index.html file doesn’t exist yet. Django will automatically load templates from the template directory. Create a folder called templates in the blog app and inside it, create a file called index.html. The folder directory should look like this:

Add the following code in index.html

Now, we’ll create our blog URLs. Create the file urls.py in the blog directory and write the URL path for serving the index page.

Now, if you navigate to http://127.0.0.1:8000/home, you should see the following page updated with this new content.

home pagehome pagehome page

Embed Data From the Database

The next step is to add dynamic content from the database. To accomplish this, Django has a templating language that allows you to embed variables with curly braces. Change the middle section of your page to look like this:

We can then pass in values to these variable placeholders from the views.py file by creating a dictionary of values.

Save and refresh, and you should see that you’re now passing in content to a template from your views file. The final step is to get data from our database and pass that in instead. Luckily, we can do this without SQL queries using Django’s models. Now go to blog/views.py and update the code to fetch data from the database.

Next, update the template to access this data.

Here, we can access all the data in our table in the views.py file, then select only the first ten entries. We pass this data into the template, loop through the entries and display the data with the HTML of our site.

Django’s Admin System

The last thing we need to do today is review Django’s administration system. This is a really powerful feature of Django that lets you manage your site without writing any more code, as you would have to if you were creating a site from scratch. To let the admin control your posts table, we’ll register our Post model in Django admin and add some data in the database. Open blog/admin.py and add the following code.

You should now be able to add new blog entries by visiting http://127.0.0.1:8000/admin/blog/post/.

That’s all there is to do. You’ve just created a fully functioning, albeit simple, blog. To finish this lesson, we’re going to look at installing Django on a web server.

Installing on a Web Server

There are two types of web hosting, and which one you have will affect whether you can use Django. If you have shared hosting, you’re entirely at the mercy of your host.

Many cheap web hosts don’t support Python. While PHP is nearly guaranteed, support for other languages often isn’t. You’ll have to check the control panel to determine if Python (and Django) are available. Obviously the process is slightly different with every host. Almost all hosting runs on Apache, and we can use it to host Django, using the mod_wsgi or mod_python Apache modules.

Most web hosts run scripts in several languages using CGI. Django can run on FastCGI, and also, theoretically, on CGI, but this is not officially supported and would be far too slow for an actual production website. You’ll need to check if these are installed. They’re usually found under a heading, like “CGI and Scripting Language Support”.

If you have VPS hosting, or are lucky enough to have a dedicated server, your life is much easier. Usually these come with Python preinstalled, and from there, you only need to follow the same steps we went through to get a local copy of Django running. If you don’t have Python, you can install it with a package manager. Your system may even come with Django.

Once you’ve installed Django on your server, upload the site you just made using any file transfer client. You can put the files anywhere, but keep them out of the public folder, or anyone will be able to see the source code of your site. I use /home for all my projects.

Next, create a MySQL database, called django_blog on your server. You’ll have to create your account for the admin control panel again, but this is a one-time thing.

If you try and run this, you might receive an error, and that’s because the settings for the server are different those on your local computer. You may need to change the database password within settings.py, but depending on your server configuration, you may also encounter other issues. Google is your friend in these situations!

To run the server this time, the command is slightly different. You have to specify an IP address and port so that you can access the site over the internet.

If you visit your site in a web browser, on port 8000, you should see your site!

Conclusion

That’s it for this lesson…and our series. I hope you’ve learned a number of useful skills over these past five lessons, and that you’re ready to go on and learn even more Python in the future. If you like the look of Django, and wish to continue increasing your knowledge of the framework, here’s some additional tutorials on the subject.

As always, I’m happy to discuss any questions about this tutorial or Python in general within the comments. Thanks for reading.

This post has been updated with contributions from Esther Vaati. Esther is a software developer and writer for Envato Tuts+.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Giles Lavelle

So, how do you get started creating websites with Python? Well, you could do it all yourself, and write a program that runs on a web server, accepting page requests and serving up responses in the form of HTML and other resources. However, that’s a lot of work, so why go to all the trouble when there are plenty of existing tools out there to do the job for you? These tools are called frameworks, and they're what we’ll use today to create our website.

Python Frameworks

There are quite a few Python web frameworks, but here are some of the best:

  • Django: We're going to use this today. It has a huge set of features, but remains simple to use. The documentation is also excellent, so if you get stuck, you'll have the easiest time solving your problem with Django.
  • Flask: Flask is a lightweight web application micro-framework designed to be easy to get started due to the many extensions that make adding new functionality easy.
  • FastAPI: FastAPI  is a modern  high-performance web framework for building APIs with Python 3.6+. It is also easy to use and offers autocompletion and linting, making writing code faster than other frameworks.
  • Falcon: Falcon is a minimalist web framework for building fast web APIs and app back-ends.  Falcon offers a clean design that uses HTTP and the REST architectural style for building API's quickly.

A more comprehensive list can be found on the Python website if you're in need of additional options. Today we’re going to set Django up for development on a local machine, and then build a simple blog. We're also going to review the process of installing it on a remote web server.

Installing Django

We'll be performing most of our work today in the terminal. This should all work on Mac and Linux; however, if you're running Windows, the process is somewhat different. A familiarity with the command line isn't necessary if you're only writing Python, though, if you're planning on using Django, or running a dynamic website in general, it's worth learning.

Terminal Tutorials

Consider reviewing these tutorials to get yourself up and running with the Terminal.

Here are the commands you need to install Django. You'll need to install version Python 3  to get it running.  First you need to create a virtual environment with the venv module. From the Python docs,

The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages in its site directories.

Create a project Directory and a virtual environment inside the project directory

Activate the virtual environment and create a new Django project.

The project directory looks like this:

Django project directoryDjango project directoryDjango project directory

What do each of these files do?

  • __init__.py tells Python that this folder is a Python package. We learned about these in the third lesson; it allows Python to import all of the scripts in the folder as modules.
  • manage.py isn’t actually part of your website; it’s a utility script that you run from the command line. It contains an array of functions for managing your site.
  • settings.py contains your website's settings. Django doesn’t use XML files for configuration; everything is Python. This file is simply a number of variables that define the setting for your site.
  • urls.py is the file that maps URLs to pages. For example, it could map yourwebsite.com/about to an About Us page.

Django refers to itself an MTV framework, which stands for Model Template View.

Apps

However none of these files on their own make a functional website. For that, we need Apps. Apps are where you write the code that makes your website function, but before we take a look at them, we need to understand a bit about Django’s design principles.

First, Django is an MVC framework, which stands for Model View Controller. Django refers to itself an MTV framework, which stands for Model Template View. It’s a slightly different approach than MVC, but fundamentally, they’re quite similar. Anyhow, MVC is an architectural pattern that provides a method for structuring your projects. It separates the code that’s used to process data from the code that manages the user interface.

Django subscribes to the DRY, or "Don’t Repeat Yourself" philosophy.

Secondly, Django subscribes to the DRY, or Don’t Repeat Yourself philosophy, which means that you should never be writing code that performs a certain task more than once. For example, in our blog, if we wrote a feature that picked a random article from the archive, and implemented this feature on multiple pages, we wouldn’t code it again each time it was needed. We’d code it once and then use it on each page.

So how does this relate to apps? Well, apps allow you to write your website in a DRY style. Each project, like the one we have here, can contain multiple apps. Conversely, each app can be part of multiple projects. Using the example from earlier, this means that if we made another site in the future that also needed a random page feature, we wouldn’t have to write it all over again. We could simply import the app from this project. Because of this, it’s important that each app serves one distinct purpose. If you write all the functionality of your site within one app, and then need to use part of it again later, you have to import it all. If you were making an eCommerce website, for example, you wouldn’t want to import all the blog features. However, if you make one app for the random feature and one app for the blog publishing system, you could pick and choose the bits that you require.

This also means that within the site, the code is well organized. If you want to alter a feature, you don’t have to search through one massive file; you can instead browse to the relevant app and change it without worrying about interfering with anything else.

The directory structure now looks like this:

Django projectDjango projectDjango project

Again, we’ve got an __init__.py file to make it a package, and three other files: models, tests and views. We don’t need to worry about tests for now, but the other two are important. Models and Views are the M and V parts of MVC.

In models, we define our data structures.

If you’ve ever worked with PHP before, you might have used PhpMyAdmin to create your MySQL tables, and then written out your SQL queries manually in your PHP scripts. In Django, it’s much easier. We define all the data structures we need in this models file, then run a command and all the necessary databases are made for us.

When you wish to access that data, you go via these models by calling method on them, instead of running raw queries. This is very helpful, because Django can use several database programs. We’re going to use MySQL today, because it’s the most powerful, and is what most hosts provide, but if we needed to switch to a different database in the future, all of the code will still be valid! In other languages, if you wanted to switch to SQLite or something similar, you would need to rewrite the code that accesses your database.

In the views file, we write the code that actually generates the web pages. This ties all the other parts together. When a user types in a URL, it is sent by the urls script we saw earlier to the views script, which then gets relevant data from the models, processes it and passes it into a template, which finally gets served up as the page the user sees. We’ll take a look at those templates shortly. They’re the easiest part - mostly HTML.

Add the blog app to the list of INSTALLED_APPS in the settings.py file.

For a blog, we’ll need a table of posts, with several fields for the title, body text, author, the time it was written, and so on. A real blog would have comments, but that’s beyond the scope of today's demo.

MySQL

These models are just a description. We need to make an actual database from them. First, however, we need MySQL running on our system. On an actual web server, this wouldn’t be a problem, because they usually have it preinstalled. 

To install MySQL type:

To check if the installation is successful, use:

This should return something like this:

Now create a MySQL database for the Django project. Run MySQL with sudo mysql and at the prompt enter:

Start the Development Server

You can now run python3.8 manange.py runserver in a new tab to start the development server.

But first we need to  configure the database settings. Let's take a look at settings.py.

You need to change the database settings first.

Now run the server and go to 127.0.0.1:8000 in your web browser. You should see the default Django page.

default Django page.default Django page.default Django page.

Configure the Blog in Django

Now let's turn our Django site into a blog. First, we need to use our models to create tables in the database by creating the following migration to effect changes made to the models.

Now run the migration to create tables in the database.

Create a Superuser

Now you can create a superuser to administer your Django app.

Set up the App URLs

Now let's set up the URLs for the app in the urls.py file. We'll include the blog URLs as from a separate file.

Create a First View

Let's create our first view, which will render a simple HTML page. Open blog/views.py and add the following code.

Create the View Template

This index.html file doesn't exist yet. Django will automatically load templates from the template directory. Create a folder called templates in the blog app and inside it, create a file called index.html. The folder directory should look like this:

Add the following code in index.html

Now, we'll create our blog URLs. Create the file urls.py in the blog directory and write the URL path for serving the index page.

Now, if you navigate to http://127.0.0.1:8000/home, you should see the following page updated with this new content.

home pagehome pagehome page

Embed Data From the Database

The next step is to add dynamic content from the database. To accomplish this, Django has a templating language that allows you to embed variables with curly braces. Change the middle section of your page to look like this:

We can then pass in values to these variable placeholders from the views.py file by creating a dictionary of values.

Save and refresh, and you should see that you're now passing in content to a template from your views file. The final step is to get data from our database and pass that in instead. Luckily, we can do this without SQL queries using Django's models. Now go to blog/views.py and update the code to fetch data from the database.

Next, update the template to access this data.

Here, we can access all the data in our table in the views.py file, then select only the first ten entries. We pass this data into the template, loop through the entries and display the data with the HTML of our site.

Django's Admin System

The last thing we need to do today is review Django's administration system. This is a really powerful feature of Django that lets you manage your site without writing any more code, as you would have to if you were creating a site from scratch. To let the admin control your posts table, we'll register our Post model in Django admin and add some data in the database. Open blog/admin.py and add the following code.

You should now be able to add new blog entries by visiting http://127.0.0.1:8000/admin/blog/post/.

That's all there is to do. You've just created a fully functioning, albeit simple, blog. To finish this lesson, we're going to look at installing Django on a web server.

Installing on a Web Server

There are two types of web hosting, and which one you have will affect whether you can use Django. If you have shared hosting, you're entirely at the mercy of your host.

Many cheap web hosts don’t support Python. While PHP is nearly guaranteed, support for other languages often isn’t. You'll have to check the control panel to determine if Python (and Django) are available. Obviously the process is slightly different with every host. Almost all hosting runs on Apache, and we can use it to host Django, using the mod_wsgi or mod_python Apache modules.

Most web hosts run scripts in several languages using CGI. Django can run on FastCGI, and also, theoretically, on CGI, but this is not officially supported and would be far too slow for an actual production website. You’ll need to check if these are installed. They’re usually found under a heading, like “CGI and Scripting Language Support”.

If you have VPS hosting, or are lucky enough to have a dedicated server, your life is much easier. Usually these come with Python preinstalled, and from there, you only need to follow the same steps we went through to get a local copy of Django running. If you don't have Python, you can install it with a package manager. Your system may even come with Django.

Once you've installed Django on your server, upload the site you just made using any file transfer client. You can put the files anywhere, but keep them out of the public folder, or anyone will be able to see the source code of your site. I use /home for all my projects.

Next, create a MySQL database, called django_blog on your server. You'll have to create your account for the admin control panel again, but this is a one-time thing.

If you try and run this, you might receive an error, and that's because the settings for the server are different those on your local computer. You may need to change the database password within settings.py, but depending on your server configuration, you may also encounter other issues. Google is your friend in these situations!

To run the server this time, the command is slightly different. You have to specify an IP address and port so that you can access the site over the internet.

If you visit your site in a web browser, on port 8000, you should see your site!

Conclusion

That's it for this lesson...and our series. I hope you've learned a number of useful skills over these past five lessons, and that you're ready to go on and learn even more Python in the future. If you like the look of Django, and wish to continue increasing your knowledge of the framework, here's some additional tutorials on the subject.

As always, I’m happy to discuss any questions about this tutorial or Python in general within the comments. Thanks for reading.

This post has been updated with contributions from Esther Vaati. Esther is a software developer and writer for Envato Tuts+.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Giles Lavelle


Print Share Comment Cite Upload Translate Updates
APA

Giles Lavelle | Sciencx (2014-01-20T02:27:34+00:00) Python from Scratch—Create a Dynamic Website. Retrieved from https://www.scien.cx/2014/01/20/python-from-scratch-create-a-dynamic-website/

MLA
" » Python from Scratch—Create a Dynamic Website." Giles Lavelle | Sciencx - Monday January 20, 2014, https://www.scien.cx/2014/01/20/python-from-scratch-create-a-dynamic-website/
HARVARD
Giles Lavelle | Sciencx Monday January 20, 2014 » Python from Scratch—Create a Dynamic Website., viewed ,<https://www.scien.cx/2014/01/20/python-from-scratch-create-a-dynamic-website/>
VANCOUVER
Giles Lavelle | Sciencx - » Python from Scratch—Create a Dynamic Website. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2014/01/20/python-from-scratch-create-a-dynamic-website/
CHICAGO
" » Python from Scratch—Create a Dynamic Website." Giles Lavelle | Sciencx - Accessed . https://www.scien.cx/2014/01/20/python-from-scratch-create-a-dynamic-website/
IEEE
" » Python from Scratch—Create a Dynamic Website." Giles Lavelle | Sciencx [Online]. Available: https://www.scien.cx/2014/01/20/python-from-scratch-create-a-dynamic-website/. [Accessed: ]
rf:citation
» Python from Scratch—Create a Dynamic Website | Giles Lavelle | Sciencx | https://www.scien.cx/2014/01/20/python-from-scratch-create-a-dynamic-website/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.