top of page

We're Learning Django



Django is a popular and powerful web framework written in Python. It's designed to simplify the process of building web applications by providing a solid foundation of tools and libraries for developers to use. Django is a full-stack web framework that includes everything from database handling to URL routing and template rendering. In this blog post, we will explore what makes Django so powerful and how it can be used to create robust web applications.


What is Django?

Django is an open-source web framework that was first released in 2005 by a group of web developers who wanted to create a better way to build web applications. The framework was named after the Belgian jazz guitarist Django Reinhardt. Django is built using the Python programming language, and it's designed to be fast, flexible, and scalable.

One of the key features of Django is its ability to handle complex web applications with ease. Django provides a robust set of tools for handling databases, authentication, security, and more. Django also has a built-in administrative interface that makes it easy to manage your application's data and users.


Why Use Django?

There are many reasons why you might choose to use Django for your web application development. Here are just a few:

  1. Rapid Development: Django provides a set of pre-built components that make it easy to get started with building a web application quickly. With Django, you don't have to spend a lot of time setting up your development environment or building out basic functionality.

  2. Scalability: Django is designed to handle web applications of all sizes, from small personal projects to large-scale enterprise applications. Django's architecture makes it easy to scale your application as your user base grows.

  3. Security: Django provides a number of built-in security features that help protect your application from common web vulnerabilities. Django also provides a user authentication system that makes it easy to manage user accounts and permissions.

  4. Community: Django has a large and active community of developers who contribute to the framework and provide support to other developers. This means that there are a lot of resources available for learning and troubleshooting.

Getting Started with Django

To get started with Django, you will need to have Python installed on your system. Once you have Python installed, you can use pip to install Django:


pip install Django

Once Django is installed, you can create a new Django project using the following command:


django-admin startproject projectname

This will create a new Django project with the given name. The project will include a number of pre-built files and directories that are used to set up your application's structure.

The next step is to create a new Django app within your project. You can do this using the following command:


python manage.py startapp appname

This will create a new app within your project with the given name. The app will include a number of pre-built files and directories that are used to define your application's functionality.


Building Your Application with Django

Now that you have your Django project and app set up, it's time to start building your application. Django provides a number of built-in tools and libraries that make it easy to build robust web applications.


Here are just a few of the things you can do with Django:

  1. Define Models: Django provides an object-relational mapping (ORM) system that makes it easy to define your application's database schema. You can define your models using Python classes, and Django will automatically create the database tables for you.

  2. Define Views: Views are used to handle requests and generate responses. Django provides a number of built-in view classes that make it easy to handle common use cases, such as rendering templates or handling form submissions.

  3. Define URLs: URLs are used to map incoming requests to specific views. Django provides a built-in URL routing system that makes it easy to define your application's URLs and connect them to the appropriate views.

  4. Render Templates: Templates are used to generate HTML output for your application. Django provides a powerful templating engine that makes it easy to create dynamic HTML pages using variables, loops, conditionals, and more.

  5. Handle Forms: Forms are used to collect user input and send it back to the server. Django provides a built-in forms library that makes it easy to create and validate forms.

  6. Manage Users: Django provides a built-in user authentication system that makes it easy to manage user accounts and permissions.

  7. Handle Files: Django provides a built-in file handling system that makes it easy to upload and manage files, such as images or documents.

Django also provides a powerful admin interface that makes it easy to manage your application's data and users. The admin interface is fully customizable, so you can tailor it to fit your application's specific needs.


Deploying Your Django Application

Once you have built your Django application, it's time to deploy it to a production server. There are many different options for deploying Django applications, depending on your specific needs and requirements.

Here are a few common options:

  1. Shared Hosting: If you have a small or low-traffic application, you may be able to deploy it on a shared hosting platform that supports Python and Django.

  2. Virtual Private Server (VPS): If you need more control over your server environment, you can deploy your Django application on a VPS. This gives you root access to the server and allows you to install and configure any necessary software.

  3. Platform as a Service (PaaS): PaaS providers, such as Heroku or Google App Engine, provide a fully-managed hosting environment for your application. This can be a good option if you want to focus on developing your application without worrying about server management.

  4. Dedicated Server: If you have a large or high-traffic application, you may need to deploy it on a dedicated server. This gives you complete control over the server environment and allows you to scale your application as needed.


Django is a powerful and flexible web framework that makes it easy to build robust web applications. With Django, you can quickly get started building your application, and then use its built-in tools and libraries to handle everything from database management to user authentication.

Django's popularity and active community also mean that there are a lot of resources available for learning and troubleshooting. Whether you're building a small personal project or a large-scale enterprise application, Django has the tools and scalability to meet your needs.

Basic Building Blocks

It is designed to work in accordance with the Django Model View Controller (https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) architecture. In other words, the relationship between the structure that deals with the data, the structure that deals with the interaction of the data with the user, and the structure that establishes the connection between these two are as independent as possible and you can easily construct modern architectures like MVC. Django simply works with the interaction of 3 basic structures: -Django Application -Template -URL



You can see what these 3 basic structures do and how they create a simple workflow in Django in the 'G-1' image. To summarize briefly: 1- The user is making an HTTP request. This request can be a GET or any other HTTP method by typing a url into the browser. 2- This request can be manipulated/used by directing the URL from which the request came to our Django App as desired in Django, or it can be directed directly to a static resource. As a result, an HTTP response is returned to the user who made the request. 3- If our business logic does not want us to return a constant value, but to perform some necessary operations, we can perform tasks such as receiving input from the user, processing this input, performing database operations, thanks to the Django App layer. 4- If the user's request points to a response that can be given with the help of a fixed resource -static files-, for example, if an HTTP request is made to get the company logo, we can do this without resorting to the Django Application layer. Thanks to these four steps, we can visualize the flow of a very simple Django Project. Let's go a little deeper and explain these basic building blocks with examples and try to better understand what the Django workflow looks like.


Django Application

Unlike the Application concept we use in daily life, Django Applications is a phenomenon that enables us to create a modular structure that we can use as "Plug-Play", and also allows us to group parts with different tasks. Thanks to this Plug-and-Play situation, you can use Django Apps prepared by other software developers for general needs. In addition, if we look at it from a functional point of view; In your project, you need to create and use Django Applications for tasks such as receiving input from the user, processing this input, performing database operations. To create a Django App, we use the manage.py script in an initial installed Django Project with the "startapp" command and the application name we want: #python manage.py startapp <app name> After this command, all python files are automatically created and waiting for us to fill them, except the “migrations” folder, which is located under the self-created contacts folder for the “contacts” api, which is an example Django App, which you can find in the image below.





To the right of the 'Example-1' image I got from one of my own projects: -The part inside the red square shows the Django Apps that came by default when you created your Django project. While it is recommended not to uninstall these apps for Django's core elements to work properly, professional users can uninstall default apps as long as they know what they are doing. -Apps in the blue square at the top show the apps that I use for user management and REST API operations of Django REST Framework, which is a 3rd party framework. -The green square at the bottom shows the "events", "contacts" and "users" apps that I created. In the User application, I manage the APIs that I keep, update and delete my user profile. I also manage user's connections and events/notifications in Contacts and Events apps.


Template

Generally, a good web framework has the ability to generate and manipulate HTML files. It should also help eliminate or reduce as much as possible copy-paste content/code duplication while doing these jobs. Django has its own special template language: Django Template Language (DTL). In addition, with “Jinja2”, which became available after Django 1.8, it is possible for us to do tasks that require higher performance (and have pros and cons that we will not dwell on for now).



Before we start using the templates, we need to specify the folder location to Django as seen in the red square in "Example-2". The result of the operation in the red square is simply to specify the location of the "templates" folder, which you can see on the left as "/project_folder_full_location/templates". “TEMPLATES_DIR” is a variable defined as TEMPLATES_DIR = “templates” in the higher part of the code in the settings.py file. As you can see, the templates folder contains 2 html files. What I was trying to do in this project was to write a code that would pull and sort the blog posts I had previously written into the database. In this context, let's examine the html files:


The section we will pay attention to in this piece of html code:


{% for post in posts %}
    <hr>
    <h2> {{ post.title }} </h2>
    <p> {{ post.description }} </p>
{% endfor %}

This html file is used by Django Application named Posts. The user request, which starts with HTTP GET through Django's URL structure, is connected with the list_posts() method of Posts Application.


def list_posts(request):
    posts = Post.objects.all()
return render(request, "posts.html", {'posts': posts})

This request is then manipulated by the list_posts method of our application. The process is to take all the posts in the database and return them to the user by processing them with the "posts.html" template. Then, our dict type posts data in posts.html, which is included in the special "for" structure we have separated above, is processed and our user sees the new html page created as a result of this process as follows:



URL

As we talked about in the Django workflow diagram, the first point of a user's interaction with Django is the URL. The user makes the request using an appropriate URL set in Django with the specified HTTP method. The example below shows the folder structure of the Django Project ItsMeBlog and the contents of the urls.py file created at the project level. Above, under the Template heading, I would like to point out that the url we use to list the posts is configured as <host>/blog/posts/. If we follow this, we can see that the "/blog" location in the project level urls.py file points to the app level urls.py file located under the blog Django App.



The urls.py file under the Blog Django App also contains information about the locations to go after the "/blog/" location. For example, "/blog/posts/" location returns the "views.list_posts" method to the user.




We continue our follow-up from the views.py file located under the blog Django App. When we look at the method named "list_posts()" there, we see that all posts in the database are taken and processed with the "posts.html" template and returned to the user.




When you follow these processes from top to bottom, we get the diagram drawn at the beginning of the article:



1- User assigns HTTP Request 2- The URL goes where it matches. This place can be a Django App or a template that returns static data. 3- If Django App is the place to go via URL, HTTP Response is provided as a result of a series of operations. If it is a template or a fixed data, the relevant data is returned to the user as HTTP Response.



How to Set Django Startup Settings?

When starting a new Django project, there are several initial settings that you will need to configure to get your website up and running. These settings will help Django connect to your database, manage your static files, and handle your application's settings.

Here are the key steps for setting up your Django website:

  1. Create a New Django Project: The first step is to create a new Django project. To do this, open up your terminal or command prompt and run the command:


django-admin startproject projectname

Replace projectname with the name of your project. This will create a new directory with the same name as your project.


2. Configure the Database: By default, Django uses an SQLite database, which is a lightweight database that is suitable for small to medium-sized projects. However, for larger projects or applications with heavy traffic, you may need to use a different database such as PostgreSQL or MySQL. To configure the database, open the settings.py file in your project directory and update the DATABASES setting:


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'database_name',
        'USER': 'database_user',
        'PASSWORD': 'database_password',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

Replace database_name, database_user, and database_password with the appropriate values for your database.


3. Configure Static Files: Static files are files such as CSS, JavaScript, and images that are served directly by the web server. To configure static files, add the following code to the bottom of your settings.py file:


STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

This tells Django where to find your static files and where to store them when you run the collectstatic command.


4. Configure Application Settings: In Django, each application can have its own settings. To create a new application, run the command:


python manage.py startapp appname

Replace appname with the name of your application. Once you have created your application, you can add settings to its apps.py file, such as:


from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'myapp'
    verbose_name = 'My Application'

This sets the name and verbose name of your application.


5. Add URLs: Finally, you need to add URLs to your project so that Django knows which views to use for each request. To do this, create a urls.py file in your application directory and add the following code:


from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('about/', views.about, name='about'),
]

This creates two URL patterns: one for the home page and one for the about page. Replace views.home and views.about with the appropriate views for your application.

By following these steps, you can set up the initial settings for your Django website and start building your application. As you continue to develop your website, you can customize these settings and add new functionality as needed.


Class-Based Views and Function-Based Views in Django


In Django, there are two main types of views that you can use to define the behavior of your website: class-based views and function-based views. Each type of view has its own advantages and disadvantages, and choosing the right one for your project will depend on your specific needs and preferences.

Function-Based Views (FBVs)

Function-based views (FBVs) are the simplest and most straightforward way to define views in Django. In an FBV, you define a Python function that takes a request object as its argument and returns an HTTP response object. Here's an example of a simple FBV that renders a basic HTML template:


from django.shortcuts import render

def my_view(request):
    context = {'message': 'Hello, world!'}
    return render(request, 'my_template.html', context)

In this example, the my_view function takes a request object as its argument and uses the render function to generate an HTTP response that renders the my_template.html template with a context variable containing the message "Hello, world!".

One of the main advantages of FBVs is their simplicity and flexibility. They are easy to write and understand, and can be used to implement a wide variety of functionality. Additionally, FBVs can be used in conjunction with decorators to add additional functionality, such as authentication or caching.

Class-Based Views (CBVs)

Class-based views (CBVs) are a more powerful and sophisticated way to define views in Django. In a CBV, you define a Python class that inherits from one of Django's built-in view classes, and then define methods on that class to handle specific HTTP methods (such as GET or POST). Here's an example of a simple CBV that does the same thing as the FBV example above:


from django.views import View
from django.shortcuts import render

class MyView(View):
    def get(self, request):
        context = {'message': 'Hello, world!'}
        return render(request, 'my_template.html', context)

In this example, the MyView class inherits from the View class, which provides a basic framework for handling HTTP requests. The get method is defined to handle GET requests, and uses the render function to generate an HTTP response that renders the my_template.html template with a context variable containing the message "Hello, world!".

One of the main advantages of CBVs is their modularity and reusability. Because CBVs are based on classes, you can easily subclass them to create new views with similar functionality. Additionally, CBVs provide a lot of built-in functionality that can simplify your code and make it easier to maintain, such as handling HTTP redirects and form processing.

Choosing Between FBVs and CBVs

When choosing between FBVs and CBVs in Django, there are a few key factors to consider:

  • Complexity: If your view is simple and straightforward, an FBV may be the best choice. If your view is more complex and requires a lot of functionality, a CBV may be a better fit.

  • Reusability: If you anticipate needing to create multiple views with similar functionality, a CBV may be a better choice because it allows you to define a base class that can be subclassed.

  • Familiarity: If you are more comfortable with functional programming, FBVs may be easier to work with. If you are more comfortable with object-oriented programming, CBVs may be a better fit.

Ultimately, the choice between FBVs and CBVs will depend on your specific needs and preferences. Django provides both options to give you the flexibility to choose the approach that works best for you.


How to Convert Django Website to Progressive Web App (PWA) / Progressive Web App?

Progressive Web Apps (PWAs) are web applications that provide a native-like experience to users, including offline functionality, push notifications, and the ability to be installed on the home screen of a device. Converting a Django website to a PWA can provide a better user experience and increase engagement with your application. Here are the steps to convert a Django website to a PWA:

  1. Add a service worker: A service worker is a JavaScript file that runs in the background and enables offline functionality and caching. To add a service worker to your Django website, you can use a library such as Workbox. Workbox provides pre-built service worker code and utilities to make it easier to add offline functionality and caching to your application.

  2. Configure a web app manifest: A web app manifest is a JSON file that provides metadata about your PWA, such as its name, icons, and start URL. To create a web app manifest for your Django website, you can use the Django PWA library. The library provides a template for the manifest file, as well as utilities for configuring other PWA features such as push notifications and app installation.

  3. Optimize for mobile: PWAs are designed to provide a native-like experience on mobile devices, so it's important to optimize your Django website for mobile. This includes using responsive design to ensure that your application works well on smaller screens, and minimizing the amount of data that needs to be downloaded.

  4. Add push notifications: Push notifications are an important feature of PWAs that can help increase user engagement. To add push notifications to your Django website, you can use a third-party service such as Firebase Cloud Messaging or OneSignal. These services provide APIs that allow you to send push notifications to users who have installed your PWA.

  5. Test and deploy: Once you've added the necessary features to your Django website to convert it to a PWA, it's important to test it thoroughly to ensure that it works as expected. You can use tools such as Lighthouse to test the performance and accessibility of your PWA. Once you're satisfied with the results, you can deploy your PWA to a web server and make it available to users.

In summary, converting a Django website to a PWA involves adding a service worker, configuring a web app manifest, optimizing for mobile, adding push notifications, and testing and deploying your PWA. With these steps, you can provide a native-like experience to users and increase engagement with your application.

20 views0 comments

Recent Posts

See All
bottom of page