Python is a versatile and powerful programming language that can be used for web development and other applications. This guide will teach you how to use Python for web development, from basic concepts to more advanced techniques. Whether you're a beginner or an intermediate Python programmer, this guide will help you get started with web development.
What is Python and what are its features?
Python is a widely used high-level interpreted programming language for developing web applications, software applications, mobile applications, data analysis and machine learning(automated machines). Python is simple to learn and easy to use, meaning you can quickly get started with web development.
In this article, you'll learn how to use Python to create a basic web application. You'll learn how to create a web page, navigate between pages, and use Python modules to do things like processing data or accessing databases. By the end of this tutorial, you'll have a basic understanding of how Python works and you'll be ready to start developing your own web applications.
Getting started with Python for web development
To get started in website development in python, you need to have python installed on your laptop or PC. Once installed, then you need to have an IDE (Integrated development environment software) where to write your code. Some of the best IDES are Pycharm, Vscode, eclipse, IntelliJ idea, and many others.
So, no where to get python just go to the internet and follow the procedures to install python. Make sure to install the latest version.
After python and your favorite IDE are installed, then you're ready to go! Keep reading.
First, we’ll create a new project in Python and get started with the basics of coding. Next, we’ll build a simple web application that displays a list of events, and finally, we’ll take a look at some of the advanced features of Python and how you can use them to enhance your web development workflow.
Python libraries and frameworks for web development.
Django
Django is a python framework that is widely used over the years to build web applications, blogs and softwares. Django is wide and there it's better to practice some functionalities and earn your interests. You can even see the whole documentation of Django here visit Django docs.
Even successfully large websites have been using it to develop dynamic large scale websites and applications. So don't hesitate to use Django.
Flask
Flask is an alternative of django and it's use for developing website applications especially. Flask is a powerful framework because it lets the developer quickly create and design an application within a short period of time unlike django which takes some time to set up.
Flask is now used by a lot of companies to build websites.
Creating a simple website using python
In this Python for Web Development guide, you will learn how to use Python for web development by creating a simple web application, navigating the web browser, and handling data. By the end of the course, you will have the skills needed to develop your own web applications in Python.
In this guide, we are going to use the Django framework for building our website since it's my favorite framework. Others might be interested in Flask but it's better to stick to what you know. You may either choose Flask or Django but for me I highly recommend Django.
So let's get started
Hope you have installed python and your IDE so no need to go back back. So now you need to install the Django framework in order to get started.
Open your command prompt on windows in the current directory and run the following command to install django.
pip install django
After installing Django you will see Django successfully installed. And you can check django version by running a command
django-admin –version
~4.0.5
and you will see the latest version.
Let's create our first project.
Creating our project
Now you have everything ready and it's time to create our project
Go to the command prompt or terminal and make sure you're in the current directory/folder. And then run. Here I will name my project events but you can go ahead and use any name you want.
django-admin startproject events
After creating the project you will see automatically added files to your project and it will look like this.
events
events/folder
d.b.sqlite3
manage.py
And when you open the events folder you will see auto generated files like this.
events
events/folder
__pycache__
__init__.py
asgi.py
settings.py
wsgi.py
d.b.sqlite3
manage.py
So now let's create our app in our project.
Creating our first application (app)
To create an app in django go to the terminal and go to the project's name folder and run.
cd events
python manage.py startapp events app
and your app will be created inside the project and your structure will be like this.
events
events/folder
eventsapp/folder
d.b.sqlite3
manage.py
And when you open up the events app you should see the structure of your auto generated files in this format.
events
events/folder
eventsapp/folder
__pycache__
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
d.b.sqlite3
manage.py
Setting our project and app
So now it's time to set our app(events app).
Go to events/settings.py under the installed app and add your events app.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'eventsapp',
]
Don't forget to add your app urls in the project folder in urls.py file. Go to events/urls.py file and add your app.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('eventsapp.urls')),
]
Writing our first view
Everything is ready to go. After you have configured everything, now you're on the right path towards your first website. To create our views, go to eventsapp/views.py in the eventsapp and write the following code.
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def eventsPage(request):
return HttpResponse('This is my first website with python')
Here you're on the right way. So let's run the app and see the response. Run this command
cd events
python manage.py runserver
And open the link in the browser at http://127.0.0.1:8000.
That's pretty cool and you have made it. To get the real website, we need to render an html page. In the eventsapp/views.py
def eventsPage(request):
return render(request, 'events.html')
Assigning view to the url
Since you're first view is done, when you run your server it will result into an error because the view will not find the html file to render to in order to complete a request. So to create a url path, go to eventsapp and create a new file called urls.py and write the following code.
from django.urls import path
from . import views
urlpatterns = [
path(' ', views.eventsPage, name='events)
]
Now that you have a url path let's relax and create our html file and connect it to the url path to complete a request.
Navigate to the eventsapp and create a new folder called templates.
Inside templates, create a new file and name it events.html and here some IDE will auto complete an html snippet to start from.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h1>My first website with python</h1>
</body>
</html>
After this, run the server in the terminal by running
python manage.py runserver to see the magic.
Databases(creating our first model)
Now that we have our website up and running, you may stop here if you're a beginner and play around with the above steps to create a real website; however, if you want a dynamic website, you may go a head and try this.
I will not go deep into dynamic apps but I will show you the basics and you can see more about creating dynamic pages by visiting django documentation.
So the first thing to do is create model classes to store our event objects in our database and will be using sqlite3 database.
Let's get started.
In the eventsapp/models.py file write the following code
from django.db import models
#create your models
class Event(models.Model):
event_name = models.CharField(max_length=100)
description = models.TextField(blank=True)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
This is our first model class and next is to register it in the eventsapp/admin.py
And to register your model, you need to write this code.
from django.contrib import admin
from . models import * #imported all the models in the eventsapp
# Register your models here.
admin.site.register(Event)
After you have registered your models, go to the terminal, events and run
python manage.py makemigrations
to make migrations
Again run
python manage.py migrate
to apply migrations
Creating a super user to access Django admin
You have configured everything and are running ok but you can't access the database tables you migrated. The simple trick here is to create a super user in order to access the admin panel of your application.
Note: A superuser is the one who is controlling the database of your application, adds events, deletes events, users, and updates the database.
To create a superuser you need to run
python manage.py createsuperuser
Go ahead and fill in your details like email address, password and then confirm your password. Navigate to http://127.0.0.1:8000/admin and login. After logging in, you can start to add your events as many as you can.
Accessing the values in the database
To access the database objects in django we need to use a templating engine called jinja and must know its syntax in order to access it in the html page. For the backend in the eventsapp/views.py, write this code below.
def eventsPage(request):
events = Event.objects.all()
context = {'events':events}
return render(request, 'events.html', context)
After writing this code, go to eventsapp/events.html
Here we use Jinja syntax, it's syntax is like this.
{% do something %} and to access the values {{ value name }}
<div class="container">
<h1>Events</h1>
<br>
{% for event in events %}
<h3>{{ event.event_name }}</h3>
<p>{{event.description}}</p>
{% endfor %}
</div>
Congratulations! You have created your first simple website using python and django
What next after here? Well, you will keep on practicing and get familiar with Django and python syntax. And here I can say that your website is now functioning well. Where you're lost or don't understand, you can visit django docs or ask on google and stackoverflow will provide as many answers as you want.
Conclusion
If you're looking to get into web development, Python may be the right language for you. Python is attractive to developers for a few key reasons.
It's an interpreted language, which means that you can run your code quickly and easily on a wide range of platforms. This means you can start developing on your computer, and then move your code to a more powerful device, like a server or a mobile device, without having to rewrite any code.