Code

Building a Django App from Scratch: Installing the Framework, Configuring the Engine, and Setting Up Recordings

Building a Django App from Scratch: Installing the Framework, Configuring the Engine, and Setting Up Recordings

Course with Employment: "Web Developer"

Learn more

Django is a powerful web development framework created in the Python programming language in 2005. It enables developers to quickly and efficiently create websites and web applications of varying complexity, from simple blogs to large platforms such as Spotify. One of Django's key advantages is its modular architecture, which simplifies the process of developing and extending application functionality. The ease of learning the framework makes it a popular choice for both novice and experienced developers. Django also offers many built-in tools, such as a database management system, admin panel, and security tools, which significantly speeds up the development process.

In this article, we will look at how to create web applications with Django. We'll explore the framework's structure and develop our first web application—a blog engine that allows you to publish and edit posts. This is the first part of the Django tutorial; in the next part, we'll focus on customizing the admin panel and improving the appearance of our posts.

Why Learn Django

According to Stack Overflow's 2022 research, Django ranks ninth among web frameworks, ahead of popular technologies like Spring and Ruby on Rails. Django continues to attract the attention of developers thanks to its simplicity, flexibility, and powerful capabilities for building web applications. This framework provides rapid development and scalability, making it an ideal choice for startups and large projects.

The Django framework is located in the middle of the list of popular web frameworks. Screenshot: Stack Overflow

Django is a popular web development framework used by many well-known services, such as Instagram, Pinterest, Spotify, Last.fm, and the Mozilla website. This tool is not limited to large corporate projects; it is also actively used to create personal websites, including blogs, photo galleries, and portfolios. Thanks to its flexibility and convenience, Django allows developers to quickly and efficiently develop web applications of varying complexity.

One of the main advantages of the Django framework is the DRY (Don't Repeat Yourself) principle, which means that code written once can be reused in different projects. Thanks to this approach, developers can significantly reduce development time and effort by avoiding code duplication. In this regard, Django is often compared to a Lego constructor, where each element can be combined and reused to create new applications. This aspect makes Django an excellent choice for developing complex web applications, allowing for efficient code management and simplifying the process of updating and maintaining it. Django has many advantages beyond the DRY principle. It is a powerful web framework that ensures rapid development and clean design. It offers high security, making it an ideal choice for creating secure applications. In addition, Django supports scalability, allowing developers to easily adapt their projects to growing requirements. The framework includes convenient tools for working with databases, which simplifies the process of creating and managing models. Also worth noting is the active community and extensive documentation, which greatly simplifies learning and resolving issues. Django is suitable for creating various types of applications, from simple websites to complex enterprise solutions. Clear and simple syntax (it is written in Python); A large number of ready-made templates and modules that facilitate development and eliminate the need for external libraries or extensions. This helps avoid conflicts between them after updates;

  • detailed documentation and a large community. If you have a question about the code, you can easily find an answer on Stack Overflow or other sites.
  • Django Structure

    The framework includes four key components that provide its functionality and efficiency. These components play an important role in the structure and operation of the framework, allowing developers to create powerful and responsive applications. Understanding these core elements will help you use the framework more effectively in your projects.

    • Models — interact with the database and retrieve the information that needs to be displayed in the browser.
    • Views — process the request and access the model, telling it what information needs to be retrieved from the database.
    • Templates — show how exactly the information retrieved from the database should be displayed.
    • URL routes (URL dispatcher) — redirect the HTTP request from the browser to the views.

    At first glance, the structure may seem complex, but in practice it becomes clear and accessible. We'll cover each aspect in detail, so you'll quickly master all the necessary elements.

    Installing Django and Setting Up a Virtual Environment

    Before installing Django and virtualenv, make sure Python is installed on your computer. To check for Python and its version, open a terminal in your IDE or operating system and run the following command:

    If Python is installed on your device, the terminal will display its version. To check the Python version, open a terminal and enter the command «python —version» or «python3 —version». This will ensure that Python is successfully installed and available for use. If you see the version number, the installation was successful, and you can start developing Python applications.

    Screenshot: Django / Skillbox Media

    If Python isn't installed on your computer, you can refer to our other guide to learn how to install it. After successfully installing Python, the next step is to set up a virtual environment, which will allow you to manage project dependencies more efficiently.

    A virtual environment created with virtualenv is an effective tool for dependency management and project isolation. It allows you to install the necessary libraries and packages locally for each project, which eliminates conflicts between dependencies of different applications and simplifies their maintenance. Installing virtualenv is done through the terminal, making the process accessible and convenient for developers. Using virtual environments is a best practice in Python development, keeping projects clean and tidy.

    To begin, create a project directory in which we will deploy the virtual environment. This will isolate the dependencies and settings necessary for your project to work.

    The mkdir command creates a new directory called blog, and the cd command is used to change to this directory in the terminal. Now the blog folder will become the main place for organizing the virtual environment and storing all the files related to our Django project. This simplifies project management and helps to structure it.

    Let's create a virtual environment in the development directory. Virtual environments allow you to isolate project dependencies and manage them more efficiently. This is especially useful when working with multiple projects, as each environment can have its own packages and library versions. Make sure you have Python and the pip package manager installed. Then, navigate to the development folder and run the command to create a virtual environment. Afterward, activate it to begin installing the required dependencies and developing your project.

    Activating requires several steps, otherwise, the functionality will not be available. Activation ensures that the system will function correctly and all features will be available to the user.

    After activating the virtual environment, you can observe changes in its display in the terminal. Specifically, this is evidenced by the fact that in the second line, the name of the current environment has changed from (base) to (venv). This indicates that we have successfully activated the virtual environment, which allows us to isolate dependencies and packages for a specific project.

    Screenshot: Django / Skillbox Media

    The Django framework is installed via the terminal. To do this, open the command line and run the appropriate command. Make sure you have the latest version of Python installed, as Django requires Python to function. Installation is performed using the pip package manager. This allows you to easily manage project dependencies. Once the installation is complete, you can begin developing web applications with Django, leveraging its powerful capabilities for creating and managing databases, processing queries, and building interfaces.

    The result of installation represents the successful configuration and functioning of the system or software. This includes the proper integration of all components, which ensures stable operation and optimal performance. After installation, users can expect access to all provided features and capabilities, contributing to increased productivity. It is also important to note that if you encounter any problems, you should refer to the troubleshooting instructions or contact technical support for qualified assistance.

    Screenshot: Django / Skillbox Media

    The last line confirms successful installation. We installed the latest version of Django, as well as two additional libraries that extend the framework's functionality and facilitate development.

    • asgiref is an interface for interacting with asynchronous web services, platforms, and Python applications;
    • sqlparse is a simple parser for working with SQL databases.

    Make sure you have completed all the items on the checklist. This is a key step to achieving a successful result. Checking each item helps avoid errors and improve the quality of your work. Stick to the list to ensure that all important aspects are considered and completed. This will save you time and resources, and also ensure the effective completion of tasks. A systematic approach to completing tasks will significantly improve your productivity and the quality of the final product.

    • checked that you have Python;
    • created a directory and deployed a virtual environment in it using virtualenv;
    • installed Django in the same folder.

    Now you can start developing the project.

    Learning the basic concepts of the Django framework is most effectively done through practice. In this article, we will create a web application for a simple blog with text posts and discuss its functioning in detail. The development process will be divided into seven simple steps, which will help you better understand the principle of modularity.

    Preparing and Configuring the Environment

    Creating the basic project structure through the terminal is the easiest and most effective way. Using the command line, you can quickly and easily set up all the necessary directories and files, significantly speeding up the development process. Use commands to initialize the project, create folders, and set up configurations to keep your project organized and structured from the start. This will help you avoid unnecessary effort and simplify future project development.

    Remember the period at the end of the command, as it indicates that the project is created in the current directory without creating a new folder. If the period is missing, the command will fail, and the terminal will return an error. Correct use of this syntax ensures successful project creation and saves time on additional steps.

    If the installation process is successful, Django will create a manage.py file in the blog directory, which is responsible for executing various commands in the terminal. In addition, a blog folder will be created, containing five files necessary for the application to work.

    Screenshot: Django / Skillbox Media

    We won't go into detail about the purpose of each of these files, as not all of them require editing. If you're interested in information about specific files, simply open them—each one has its function listed at the top.

    To store blog posts, you need to create a database. Django supports a variety of databases, but uses SQLite by default. This database is well suited for our needs, as we have only one user and a simple post structure. Using SQLite ensures ease of setup and management, which is especially important for smaller projects.

    Creating an SQLite database is possible with just one command. This makes working with SQLite incredibly simple and convenient for developers. This makes development and data management more efficient, which is especially important for creating lightweight applications and prototyping. SQLite allows for rapid development without the need for complex setups or additional dependencies.

    In the project directory, you will find the db.sqlite3 file, which represents our database.

    To get started with our blog, you need to create a superuser with administrative rights. This can be done with a simple command. The superuser has full access rights and can manage all aspects of the blog, ensuring efficient administration and content management. Creating a superuser is an important step in setting up and optimizing your blog.

    After executing the command, the terminal will prompt you to enter a username, email address, and set a password. Be sure to save this information, as you will need it later.

    The runserver command is an important tool that we will work with throughout the development process. It starts the built-in web server, designed for testing applications on the local computer. Using runserver allows developers to quickly test code changes and test the application’s functionality without having to deploy it to a remote server. This makes the development process more efficient and convenient.

    By default, the server runs on port 8000 and is accessible at 127.0.0.1, which means that it is only accessible on the local computer. You can change the port and IP address if necessary, but this is not the goal at the moment.

    Once the server starts, you can open the Django project in your browser by entering the address http://127.0.0.1:8000 or http://localhost:8000. If all the previous steps were followed correctly, the Django welcome window will be displayed on the screen. This confirms that your project has been successfully configured and launched, allowing you to move on to further development and testing of your web application. Make sure the server is running without errors to avoid potential problems in the future.

    Screenshot: Django / Skillbox Media

    Let's finish Let's configure our project and go to the administration page at http://localhost:8000/admin. Enter the superuser name and password specified in the previous step. After that, you will have access to the admin panel, where you can manage the content and settings of your project.

    Screenshot: Django / Skillbox Media

    The admin panel is a key tool for managing your site's content and users. It's important to note that it will be essential in the subsequent stages of developing and customizing your blog. With the admin panel, you can effectively organize posts, edit content, and manage user interactions.

    Adding an Application to the Project

    A Django project consists of one or more applications. It can be difficult for beginning developers to distinguish between the terms "project" and "application," but the difference between them is quite simple. A project is a container that brings together all the applications and settings necessary for a web application to function. An application, in turn, is a narrower unit that performs a specific task or set of functions within the project. Each application can be reused in other projects, which makes Django a powerful tool for website development. Understanding these differences will help you organize and structure your code more effectively.

    • An application is a module of our project. It can be associated with specific functions or a group of users. For example, if we were creating a social network, we would create separate applications for regular users, group owners, and content moderators.
    • A project is our entire program. It can consist of a single application (which is what we will do) or several.

    Dividing a project's functions into different applications allows for code reuse across different projects. This allows you to quickly integrate the necessary functionality without having to rewrite the code. This approach improves development efficiency and simplifies project maintenance and updates.

    To store and display text notes, it is enough to use a single application, which we will call entries. Before creating this application, you need to stop the server. To do this, run the command in the terminal by pressing Ctrl + C for Windows or Control + C for macOS.

    Now let's start creating the application. First, let's define its main functions and structure. Pay attention to the choice of technologies and tools that will be used during the development process. This will allow us to optimize performance and ensure ease of use of the application. Next, we'll create the project architecture, including the frontend, backend, and database. After that, we'll move on to coding, focusing on cleanliness and efficiency. Don't forget to test at every stage to ensure stable operation and identify any potential errors. Finally, we'll prepare the application for deployment and ensure it meets all user requirements and modern standards.

    This command will create an entries folder in the blog project, containing a set of predefined files. Please note that all terminal commands should be entered within the project directory. We'll be working with some of these files later.

    Screenshot: Django / Skillbox Media

    Django is not yet recognizes the created entries application. To enable it, you need to add the application name to the end of the INSTALLED_APPS list in the blog/settings.py file. This will allow Django to see and use the functionality of the entries application in your project.

    The entries application has been successfully integrated into our project, and Django now recognizes its configurations. One of the key configurations is the model, which defines the structure of blog entries in the database. This model defines the attributes and data types needed to store information about entries, such as title, content, publication date, and author. Correctly defining the model ensures efficient interaction with the database and simplifies blog content management.

    Creating a model for entries

    Once the database has been created, you need to create a table to store blog entries. In Django, this is accomplished using model classes. As with regular Python classes, model names are conventionally specified in the singular and capitalized. Since our application is called entries, the model will be named Entry. Creating an Entry model will allow you to effectively manage blog entries, providing a convenient interface for interacting with the database.

    Entry fields are the key elements that make up any blog entry. They appear as form fields on the website and as columns in the database. Each blog entry has three main elements:

    • title — the title;
    • content — the main text;
    • date_created — the date and time it was created.

    In the entries/models.py file, we need to start by importing the timezone module from django.utils. We then need to create an Entry class that describes the main characteristics of the model. The code comments will explain the purpose of each part. This will help us better understand the structure and functionality of the model, and will also simplify our further work with it.

    By importing the timezone module, we can use the timezone.now parameter as the default value for the date_created field. This will simplify the process of creating new entries, as we won’t need to manually specify the date and time. This feature will be useful in the future when we develop a form for creating posts.

    Django automatically adds a unique primary key id for each entry, in addition to the title, content, and date_created fields. By default, the string representation of an entry with a primary key of 1 will be displayed as Entry object (1). To improve the readability and identification of blog entries, we can override the __str__() method. This will display the entry title instead of the standard numbering, which will make the interface more convenient and understandable for users.

    It is important to manually set the verbose_name_plural variable to correctly display plurals in Django. Without this, the framework will incorrectly display the plural form of the word Entry as Entrys, while the correct form is Entries. Setting this variable helps avoid errors and ensures the correct display of names in the admin panel and other parts of the application.

    To display the Entry model in the Django admin panel, you must register it in the entries/admin.py file. This will allow you to manage model records through the admin interface, which will significantly simplify the process of working with data. Registering a model involves importing the necessary classes and using the admin.register() decorator, which provides access to the model and its settings in the admin interface. Properly configuring the model in the admin panel improves the user experience and makes data management more convenient and efficient.

    If you do not perform this action, Django will not generate an error, but it will be impossible to manage the blog model through the admin panel. This will create significant inconvenience when working with content and administering the site.

    After adding a new class and registering it in the Django admin panel, you need to create migration files and execute them. To do this, use the makemigrations command, which generates migrations, and then the migrate command, which applies them to the database. Both commands are entered in the terminal.

    After the migration is complete, go to the admin panel at http://localhost:8000/admin. This panel now has a new section, "Entries," linked to our app. Now you can manage entries, add new ones, and edit existing ones. Use this section to effectively manage your application content.

    Screenshot: Django / Skillbox Media

    There are no posts in the current section. You can add them manually by clicking the "Add" button. However, a more convenient way is to add new blog posts through the user interface rather than the admin panel. We'll cover this process in the next section of this article. Subscribe to our Telegram channel "People and Code" and our newsletter to stay up-to-date with updates and not miss important information.

    Learn more about our offer. We provide high-quality services to help you achieve your goals. Our team of professionals is ready to offer a personalized approach to each client. We are results-oriented and strive to exceed your expectations. Contact us for more information and start your path to success today.

    Building a Django App. Part 2. Developing the Frontend and Admin Panel

    In the second part of our guide to building a Django app, we will focus on developing the frontend and admin panel. This stage is important for ensuring a seamless user experience with your application.

    We will start by setting up the Django admin panel, which provides powerful tools for managing data. We will cover how to configure models, add custom fields, and modify the admin interface to suit your requirements.

    After that, we will move on to the frontend. We will discuss how to use Django templates to create dynamic web pages, as well as integrating CSS and JavaScript to improve the user experience. We'll also cover using libraries like Bootstrap to quickly create responsive interfaces. Setting up URL routing is also important to ensure users can navigate your application easily. We'll also discuss optimizing performance and security when developing the frontend. This part of the guide will help you create a functional and attractive interface for your Django application, making it more accessible and user-friendly. Read also: To enhance your experience and stay up-to-date, we recommend checking out our other articles. They contain helpful tips and tricks on a variety of topics. Our content is designed to help you understand your concerns and find optimal solutions. Don't miss the opportunity to learn more to expand your knowledge and skills. How to Make an Android App Yourself Test Can you speak the same language as a web developer?

  • How to start programming in Python
  • The court has ruled to ban Meta Platforms Inc. from operating in Russia, which deals with the social networks Facebook and Instagram. This decision is based on accusations of extremist activity.