Code

Building a Django App. Part 2: Customizing the Blog's Appearance and Admin Panel

Building a Django App. Part 2: Customizing the Blog's Appearance and Admin Panel

Free Python course ➞ A mini-course for beginners and experienced coders. Four cool projects in the portfolio, live chat with the speaker. Click and see what you can learn in the course.

Learn more

In the first part of the Django lesson, we installed the framework, developed a blogging engine, defined post components, and learned how to publish posts. Now we'll focus on the frontend: we'll give posts a neater and more attractive appearance, add buttons for interacting with content, and improve the user experience. Let's start with the fourth step, since the first three were discussed in the previous article.

Reading is an important aspect of our lives, contributing to the development of thinking, broadening horizons and improving communication skills. Regularly reading books, articles, and other materials helps expand your vocabulary and improve your education. Reading also improves concentration and attention, which is beneficial in both your personal and professional lives.

Reading also allows you to immerse yourself in different cultures and worlds, opening up new horizons and ideas. It's a great way to relax and unwind from the daily grind. Maintain your reading habit by choosing literature that inspires and interests you. Read regularly, and you will notice the positive impact on your life and development.

Creating an Application with Django. Part 1. Installing the Framework, Configuring the Engine, and Basic Records.

In this article, we'll look at developing an application based on the Django framework. In the first part, we'll focus on installing the framework itself, as well as initially configuring the engine and creating basic records. Django is a powerful web development tool that allows you to quickly create reliable and scalable applications.

Let's start by installing Django. This will require Python and the pip package manager. Make sure you have the latest versions of these tools installed. After that, run the command to install Django.

The next step is to set up the project. Create a new project using Django's built-in command and set up its configuration. During the setup process, pay attention to the database settings and other key settings that can affect the operation of your application.

In the final step of the first part, we will create basic records in the model. This will allow you to see how the database management system works in Django and how to conveniently interact with data.

Stay tuned for the next parts, where we will take a closer look at Django's functionality and learn how to build complex web applications.

Working on the frontend: customizing the display of blog posts

Posts created through the admin panel are not displayed on the site's main page. When you start the server, you'll see the standard Django welcome page. Let's make the necessary changes to fix this and display posts on the main page.

In Django, there are two main approaches to creating views: function-based and class-based. Both approaches perform the same task: accepting an HTTP request and returning a response. The main difference is that function-based views provide more granular control over the process but require more code. The choice between these methods depends on the specific requirements of the project and the developer's preferences. Class-based views can simplify code organization and logic reuse, while functions provide greater flexibility and simplicity for smaller tasks.

Creating a blog with simple functionality requires using class-based views, which is a standard approach in web application development. This method is especially convenient when interacting with database elements, as it allows for a more structured organization of the code and is easier to scale. Using class-based views simplifies maintaining and extending your blog's functionality, making it more efficient and flexible.

When using Django, you can effectively use built-in standard views. In this case, we'll be working with subclasses of DetailView and ListView. These classes will allow us to display data from the Entry model. To do this, we'll need to edit the entries/views.py file, where we'll include these views to process requests and display entry information.

In Django, HTML is automatically generated using templates. This is convenient for generating large volumes of similar content, such as blog posts. Using templates allows developers to speed up the development process and ensure consistency in data presentation. By inserting dynamic data into templates, creating and editing content becomes simpler and more efficient. Django templates provide flexibility and make it easy to adapt the page's appearance to the needs of the project.

Django requires that templates for class-based views be located in specific directories and named accordingly. This is essential for the proper functioning of the application. To comply with these requirements, create nested folders to store templates according to established standards. Make sure the directory structure and file names match Django's expectations to avoid issues with loading and rendering templates in your project.

At first glance, the path to the templates may seem confusing. We named the destination folder the same as our application to make things easier. In the future, if you decide to use this application in another project, you will be able to easily find and understand the location of the templates related to this application. This solution provides convenience and simplifies the development process, allowing you to quickly navigate the project structure.

Let's create a file called entry_list.html and add the following content to it:

Django templates support dynamic linking to CSS classes. For example, the code adds the class «{{ entry.date_created|date: ‘l’ }}», which is used to display a timestamp with the specified formatting. This means that the element receives the name of the day of the week as a class. This approach allows us to apply unique styles to entries depending on the day, which we will look at later when we start styling the blog.

Inside the entry_list loop, we have the ability to access all the fields of the Entry model. To avoid cluttering the list with unnecessary information, we will display entry details only on the page of a specific entry. To do this, we will create the entry_detail.html file in the entries/templates/entries/ directory and add the appropriate code to it. This will allow users to access full entry information without being distracted by unnecessary data in the list.

This template is designed to work with individual blog entries, so a loop for iterating over all existing entries is not used. This allows you to focus on a specific entry, improving performance and simplifying content management.

For templates to work correctly, you need to associate the generated views with URLs. In Django, this task is accomplished using the urls.py file, which handles incoming requests from users in browsers. Properly configuring routes in this file ensures access to the desired views and optimizes interaction with the application.

The urls.py file was automatically generated in the blog directory. However, for our Entries application to work, we need to create a new urls.py file in the entries folder. We need to add routes for the EntryListView and EntryDetailView views to this file to ensure correct navigation and access to entries.

The path() function must accept at least two arguments to work correctly with both views. These arguments are necessary for determining the route and passing data between the various components of the application. Proper use of the path() function enables efficient URL management and improves user experience.

  • a string name for the route, which contains the URL pattern;
  • a reference to the view in the form of the as_view() function. It is used for class-based views.

In Django, you can pass additional arguments, such as kwargs, and explicitly specify the route name. This makes it easy to reference views in your project. If you need to change the URL pattern, you do not need to update the patterns themselves, which greatly simplifies the process of developing and maintaining code. Using named routes allows for more flexible URL management and improves code readability, which is important for scalable projects.

Now that the URLs for the posts application have been created, it is necessary to integrate them into the blog's urlpatterns list. Open the diary/urls.py file and find the current urlpatterns used in the project. Currently, this list only contains one route to admin/, added by default, which provides access to the Django admin panel. To display blog entries when visiting the site at http://localhost:8000, you need to redirect the root URL to the created Entries application. To do this, make the appropriate changes to the diary/urls.py file.

Working on the blog's appearance

To create an attractive and user-friendly blog for both readers and authors, you need to develop a base template with a uniform design. This template will be located at entries/templates/entries/base.html and will serve as the basis for all blog pages. Proper design and content structuring will help improve navigation and enhance user experience.

Django offers a unique feature of template inheritance, which allows you to avoid duplicating markup. Instead of rewriting code, child templates can be easily extended. The framework automatically merges parent and child templates before rendering them, making development more efficient and simplifying the process of creating complex web applications. This feature contributes to better code structure and makes it easier to maintain.

By inserting {% load static %} at the beginning of the template file, we get the ability to reference static files using the {% static %} template tag. This allows us to conveniently specify the relative path to CSS files and other resources, ensuring their correct display on the web page. Using this construct is standard practice in Django development, it helps optimize loading and resource management.

Create a diary.css file in the entries/static/css/ directory and paste the following code into it:

Now we will link the child templates to the parent base.html template. To do this, you need to update the entries/templates/entries/entry_list.html file to match the following code:

Let's edit the entries/templates/entries/entries_detail.html file. This file is responsible for displaying detailed information about entries. Optimizing this template will help improve the user experience and increase the page's visibility in search engines. Be sure to add meta tags, titles, and descriptions that match the entry's content. It's also worth considering the use of structured data to help search engines better understand your content. Effective design of elements such as images and links will make the page more attractive and easier to navigate. We will focus on ensuring that the content is unique and informative, which will positively impact SEO.

Now both templates use the HTML structure and styles of the parent template, including the styles defined in the diary.css file. This ensures a consistent visual appearance and facilitates future editing and updating. Using a common CSS base style allows us to maintain a consistent style throughout the site, which improves the user experience and makes navigation easier.

Let's launch the Django server and review the changes to our blog. With Django, we can create a dynamic web application that manages blog content. Once the server is running, we'll see an updated interface and new features that will enhance user interaction with our site. Now our blog has become more convenient and functional, which will have a positive impact on its traffic and search engine optimization.

Screenshot: Django / Skillbox Media

Now the blog has become more attractive. However, managing posts, including adding, editing, and deleting them through the Django admin panel, remains inconvenient. We're implementing this functionality directly on the website, which will simplify the content management process and improve user experience.

Adding buttons for working with content

When working with blog posts, you need to perform four key operations. These operations are fundamental for content management and ensure effective interaction with the audience. Correct execution of these actions can improve the visibility of the site in search engines and attract more readers.

  • create a new post;
  • read a post;
  • update a post;
  • delete a post.

All of these actions are available through the control panel, but using this method can be inconvenient due to the need to open an additional window in the browser. We'll integrate these features into the blog's web interface using familiar approaches to working with views, templates, and URLs. This will improve the user experience and speed up the process of interacting with the blog's content.

In the entries/views.py file, we previously imported ListView and DetailView. Now, let's update this file by adding new views that will expand the functionality of our application. This will allow for better data management and a better user interface.

In this case, simply associating classes with the Entry model is not enough. For the EntryCreateView and EntryUpdateView classes, we explicitly specify which model fields should be presented in the form. However, for EntryDeleteView this is not necessary, since the purpose of this class is to completely delete the entry, regardless of its fields.

It is important to define where the user will be redirected after submitting the form. By default, the .get_success_url() method returns the success_url value. In the EntryUpdateView class, we override this method, passing entry.id as an argument. This allows the user to remain on the post page after editing. Instead of specifying URLs, we use the reverse_lazy method to access them by name, as specified in templates. This approach provides flexibility and ease of managing routing within the application.

Django continues to use defined names for template lookups. It's important to understand that the template naming structure plays a key role in their successful discovery. When developing Django applications, we recommend adhering to standard naming practices to simplify the process of finding and using templates. This not only speeds up development but also facilitates more efficient project management. Proper template naming avoids potential conflicts and makes them easier to localize and reuse across different parts of the application.

  • For EntryCreateView, this is entry_form.html;
  • For EntryUpdateView, this is entry_update_form.html;
  • For EntryDeleteView, this is entry_confirm_delete.html.

If Django doesn't find an entry_update_form.html file, it will automatically use entry_form.html as a fallback template, presenting the entry in its original state before it was edited. Using this functionality, we can create a universal template that will handle both cases in the entries/templates/entries/ directory. It is also important to add a basic form for submitting data, which will ensure the correct functioning of the application and improve the user interface. This approach allows for greater flexibility and usability with forms in Django, while ensuring the reliability and stability of the displayed content.

When this template is loaded in CreateView mode to create a new record, the form will be empty. Clicking the Cancel button will redirect the user to the list of all records. If the template is used in CreateUpdateView mode to edit an existing record, the form will be populated with the latest title and content. Clicking the Cancel button will return the user to the record page, and the changes will not be saved.

There are several methods for rendering a form in a Django template. When using the {{ form.as_p }} construct, Django automatically generates the fields specified in the view and wraps them in HTML paragraph tags. Be sure to include {% csrf_token %} in the form, which provides protection against cross-site request forgery and proves that the form submission was initiated by the user. This is an important step in ensuring the security of your web application.

Let's create the entry_confirm_delete.html file in the entries/templates/entries/ directory. This file will be used to confirm entry deletion. It's important to configure its contents correctly to provide a clear interface for users. We'll add informative text and buttons to confirm or cancel the action, which will improve the user experience and enhance the usability of the site. We should also consider using SEO-optimized titles and meta tags to improve the page's visibility in search engines. This will attract more users and improve the overall performance of the web application.

After creating the views and their templates, you need to configure the routes for accessing them through the web interface. To do this, add three additional routes to the urlpatterns file in entries/urls.py. Properly configured routes will ensure convenient access to your views and improve site navigation, which can positively impact SEO.

The entry-create function only requires the main path for creating a new note. Similarly, entry-update and entry-delete operations require a primary key to identify the specific entry to be updated or deleted. This ensures the accuracy and security of data processing in the system, allowing for efficient information management.

All the blog's core functions are now implemented: users can view entries, as well as create, update, and delete them, via the web interface. Let's launch the web server and go to the page for adding a new post to make sure our code works correctly.

Screenshot: Django / Skillbox Media

Everything works :It's fine, however, the interface is missing buttons for creating, updating, or deleting posts. This will be fixed in the next stage of development.

Making the blog easier to use

To create, edit, or delete a post, it's important to remember the corresponding URLs and enter them in the address bar. This can be inconvenient for users. To simplify the process, we'll add links to our views directly on the blog pages. This will improve navigation and make interaction with content more convenient and efficient.

Let's start by adding a link to create a new post in the entries/templates/entries/entry_list.html template. To do this, open the file and implement the following code in the {% block content %} block:

To ensure the ability to quickly edit and delete posts, you need to make changes to the entries/templates/entries/entry_detail.html template. The code should be placed immediately after a specific element in the template. This will allow users to efficiently manage the content on the page. Ensure your changes are consistent with the overall structure and style of the template to maintain a consistent design.

Let's open our blog and test its functionality. This will ensure all elements are working correctly and the content is optimized for users and search engines. Regular checks are essential to maintaining a high-quality blog and improving user experience.

Screenshot: Django / Skillbox Media

The buttons in the web interface successfully are functioning. All actions are performed correctly, indicating the proper integration and configuration of interface elements. Users can easily interact with the buttons, which improves the overall experience of working with the web application.

What's next?

Our blog is functioning, but it requires some improvement. We need to implement notifications about creating, editing, and deleting posts, as well as provide the administrator with the ability to mark individual posts as favorites and sort them in any order. For a more detailed study of these functions and their implementation, we recommend referring to the official documentation of the Django framework. This will help improve the functionality of the blog and increase its usability.

There are many books devoted to various examples of using the framework. Among them, three recommended publications stand out that will help you better understand its capabilities and application methods. These books contain practical examples and helpful tips, making them a great resource for developers looking to improve their skills with the framework.

  • Django for Beginners by William Vincent;
  • Django for Professionals: Producing websites with Python & Django by William Vincent;
  • Django Design Patterns and Best Practices by Arun Ravindran.

Read also:

  • Creating your first mobile app with Xamarin
  • "Data Scientist is the sexiest job of the 21st century"
  • What does a web developer do and what skills do you need for your first job?