Bytes

Create Views and Templates in Django For a Basic Website

Last Updated: 13th October, 2023

In web development, a view is a piece of code that generates a response to a user's request and determines what data and how it is displayed to the user. It is typically associated with a specific URL or endpoint and often interacts with a database or other data source to retrieve the necessary information.

On the other hand, a template is a file that defines the structure and layout of the content displayed to the user. It includes HTML, CSS, and possibly JavaScript and is populated with dynamic data by the associated view. Templates often include placeholders or template tags that are replaced with data when the view is rendered.

Creating views and templates is essential for web development because it separates the concerns of data retrieval and presentation. Views provide a clear separation of logic and presentation by determining what data is required for a response and how to retrieve and manipulate it. Templates provide a consistent and reusable structure for presenting data and allow for easy customization of the site's look and feel.

Additionally, the separation of views and templates allows for efficient collaboration between front-end and back-end developers. Back-end developers can focus on creating views that return the correct data, while front-end developers can focus on designing and implementing templates that display that data in an aesthetically pleasing way.

Understanding Views

In web development, a view is a Python function that takes a web request and returns a web response. In other words, a view is a function that defines what the user sees when they visit a particular URL on a website. A view is responsible for rendering the appropriate content and data to the user, usually in the form of an HTML page.

How views relate to URLs:

In Django, views are connected to URLs through a URLconf (URL configuration) module. The URLconf maps URLs to view functions, so when a user navigates to a particular URL, Django looks up the corresponding view function and calls it to generate the response. This mapping is usually done in the **urls.py** file of a Django application.

Anatomy of a view function:

A typical view function in Django has the following structure:

Loading...
  • The first line imports the **HttpResponse** class, which is used to generate an HTTP response to send back to the user.
  • The second line defines the view function itself. It takes a **request** object as its first argument, which contains information about the user's request (e.g. the HTTP method, headers, and body).
  • The function may also take additional arguments, as specified in the URLconf. In this example, **arg1** and **arg2** are placeholders for values that are extracted from the URL.
  • The view function processes the request, does some logic, and generates an output (in this case, the string "This is my view!").
  • Finally, the view returns an **HttpResponse** object containing the output.

Basic view function examples:

Here are some examples of basic view functions in Django:

Loading...

In the first example, the **hello_world** view simply returns a static string. In the second example, the **greet_person** view takes an argument (**name**) from the URL and uses it in the response. In the third example, the **my_template_view** view renders an HTML template (**my_template.html**) with a context variable (**message**).

Creating Templates

Templates are pre-designed or pre-built structures that define the layout and design of a webpage or web application. They provide a framework for displaying dynamic content that can be populated with data from a database or other data source. Templates are often used in web development to streamline the process of creating web pages with consistent layout and design.

Templates are closely related to views in web development. A view is a function that generates a web page or other content in response to a user request. The view interacts with the template to populate it with data and render it as an HTML page that can be displayed in a web browser. Templates provide the structure and design of the web page, while views provide dynamic content and logic.

Anatomy of a template file:

  • Head section: contains meta-information about the page, such as the title, description, and keywords.
  • Body section: contains the main content of the page.
  • Header section: contains the header of the page, which typically includes the site logo, navigation links, and search box.
  • Footer section: contains the footer of the page, which typically includes copyright information and links to other pages on the site.

Here is an example of a basic HTML template:

<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
    <meta name="description" content="This is my website.">
    <meta name="keywords" content="website, example">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>My Website</h1>
        <nav>
            <ul>
                <li><a href="/">Home</a></li>
                <li><a href="/contact">Contact</a></li>
     </ul>
    </nav>
  </header>

<main>
<h2>Welcome to my website!</h2>
<p>This is a simple example website. It is built using HTML and CSS.</p>
</main>
<footer>
<p>© 2023 My Website. All rights reserved.</p>
</footer>

</body>
</html>

In this example, the template includes a basic HTML structure with a head section that contains meta information about the page, including the title, description, and keywords. The template also includes a link to a CSS file, which is used to style the page.

The body section of the template includes a header with a site logo, navigation links, and a search box. The main content of the page is contained in a main section, which includes a welcome message and some introductory text. Finally, the footer section of the template includes copyright information and links to other pages on the site.

Overall, templates are a powerful tool in web development that can help streamline the process of creating consistent, well-designed web pages and applications. By providing a pre-built structure for displaying dynamic content, templates make it easier to create web pages that are both visually appealing and functional.

Building a Basic Website

Here is a step-by-step guide on how to create a simple Django project with an app, URL patterns, views, and templates, and run it locally:

Setting up a Django project and app

  • Install Django: **pip install django**
  • Create a Django project: **django-admin startproject myproject**
  • Create a Django app within the project: **python manage.py startapp myapp**

Creating URL patterns for the website

  • Create a **urls.py** file in the app directory (**myapp/urls.py**).
  • Define URL patterns in the **urls.py** file using the **path()** function or **re_path()** function. For example:

This defines two URL patterns: an empty path for the **home** view and a path for the **about** view.

Creating views for the website

  • Create a **views.py** file in the app directory (**myapp/views.py**).
  • Define view functions that take a request argument and return an HTTP response. For example:

Creating templates for the website

  • Create a **templates** directory in the app directory (**myapp/templates**).
  • Create HTML template files in the **templates** directory. For example, create a file called **home.html**:
<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
</head>
<body>
    <h1>Welcome to my website!</h1>
</body>
</html>
  1. Connecting views to templates
  • Update the view functions to render the HTML templates instead of returning an **HttpResponse**. For example:
Loading...

This tells Django to use the **home.html** or **about.html** template to render the view.

  1. Running the website locally
    • Start the development server: **python manage.py runserver**
    • Open a web browser and go to the URL **http://127.0.0.1:8000/** to see the home page. The **about** page can be accessed at **http://127.0.0.1:8000/about/**.

That's it! You have created a simple Django website with URL patterns, views, and templates, and are running it locally.

Conclusion

In conclusion, creating views and templates are essential in web development as they allow for the separation of concerns between data retrieval and presentation. Views determine what data is required for a response and how to retrieve and manipulate it, while templates provide a consistent and reusable structure for presenting data. By separating views and templates, efficient collaboration between front-end and back-end developers can be achieved. Views and templates are closely related, with views providing dynamic content and logic, and templates providing the structure and design of the web page. Overall, views and templates work together to generate an aesthetically pleasing website that effectively presents data to users.

Module 2: Building a Basic WebsiteCreate Views and Templates in Django For a Basic Website

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter