Home Backend Development Python Tutorial Django development: How to create a beautiful web application using Python and Django

Django development: How to create a beautiful web application using Python and Django

Jun 22, 2023 pm 12:18 PM
python django web application

Django is a popular Python web application framework that provides a powerful set of tools and engines that can help us easily build beautiful, scalable web applications.

In this article, we will introduce how to create a beautiful web application using Python and Django. We'll start by installing Django and creating a brand new Django project. Next, we'll create a simple web application and introduce how to create database models, views, and templates. Finally, we will add some styles and animations to this application to make it prettier.

1. Install Django

Before we start creating our web application, we need to install Django on the local computer. Django can be installed through the following command:

pip install Django
Copy after login

If you do not have pip installed, please install pip first. pip is a Python package manager that allows you to easily manage Python libraries and dependencies.

After the installation is complete, you can check whether Django has been installed successfully by running the following command:

django-admin --version
Copy after login

If Django has been installed successfully, you will see the version number of Django.

2. Create a new Django project

Now that we have Django installed, we can start creating our web application. First, we need to create a new Django project. A new Django project can be created with the following command:

django-admin startproject myproject
Copy after login

This command will create a new directory called "myproject" and create the basic structure of a Django project in it.

3. Create a simple web application

We have created a new Django project, now we can start creating our web application. We will create a simple web application that will allow users to publish and view posts on the website.

In order to create this web application, we need to perform the following steps:

1. Create a new Django application
2. Create a database model
3. Create views and Template

First, we will create a new Django application. A new Django application can be created with the following command:

python manage.py startapp myapp
Copy after login

This command will create a new directory called "myapp" and create the basic structure of a Django application within it.

Next, we need to create a database model. Our database model will define the Post object and describe the fields and properties of the Post object.

Create a file named "models.py" in the myapp directory and add the following code:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    pub_date = models.DateTimeField('date published')
Copy after login

In the above code, we define a file named "Post" Object, which has three attributes: title, content and pub_date.

The title and content attributes are fields of CharField and TextField type. They will store our post title and content. The pub_date attribute is a field of type DateTimeField that will store the time our post was published.

Next, we need to create views and templates. Views are where web applications handle requests, and templates determine how our web applications should be rendered in the user's browser.

Create a file named "views.py" in the myapp directory and add the following code:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Post

def index(request):
    latest_posts = Post.objects.order_by('-pub_date')[:5]
    context = {'latest_posts': latest_posts}
    return render(request, 'myapp/index.html', context)

def detail(request, post_id):
    post = Post.objects.get(pk=post_id)
    return render(request, 'myapp/detail.html', {'post': post})
Copy after login

In the above code, we define two views: index and detail . The index view will query the database for the 5 most recent posts and pass them to the template. The detail view queries the database for a specific post based on post_id and passes it to the template.

Next, we need to create the template. Create a new directory named "templates" under the myapp directory and add two HTML template files "myapp/index.html" and "myapp/detail.html".

In the "myapp/index.html" template, we will render the last 5 articles:

{% for post in latest_posts %}
    <div class="post">
        <h2 class="title">{{ post.title }}</h2>
        <p class="date">{{ post.pub_date }}</p>
        <p class="content">{{ post.content }}</p>
    </div>
{% endfor %}
Copy after login

In the "myapp/detail.html" template, we will render the specific article :

<div class="post">
    <h2 class="title">{{ post.title }}</h2>
    <p class="date">{{ post.pub_date }}</p>
    <p class="content">{{ post.content }}</p>
</div>
Copy after login

Now that we have created a simple Django web application, we can run it and see the effects. Enter the following command in the terminal to start the server:

python manage.py runserver
Copy after login

Open the browser and enter http://localhost:8000/myapp/, you will see a list of the 5 most recently published articles.

4. Add styles and animations

Now that we have created a simple web application, let's add some styles and animations to it. We will use Bootstrap framework and jQuery library to achieve this task.

First, we need to add static files to the application. Create a new directory called "static" under the myapp directory and create another directory called "myapp" inside it. Under the "myapp" directory, we will add two subdirectories, css and js. Under these two subdirectories, we will add files named "style.css" and "script.js".

In the "style.css" file, we will add some basic styles:

.post {
    background-color: #fff;
    border: 1px solid #ccc;
    margin-bottom: 20px;
    padding: 10px;
}

.title {
    color: #ff0000;
    font-size: 24px;
    font-weight: bold;
}

.date {
    color: #00ff00;
    font-size: 14px;
    font-style: italic;
}

.content {
    color: #0000ff;
    font-size: 16px;
}
Copy after login

In the "script.js" file, we will add some basic animations:

$(document).ready(function() {
    $('.post').hover(function() {
        $(this).animate({ backgroundColor: "#FEEBD4" }, 200);
    }, function() {
        $(this).animate({ backgroundColor: "#fff" }, 200);
    });
});
Copy after login

In the above code, we use the jQuery library to change the background color of each article from white to pink when the user hovers over it:

Now that we have added styles and animations to our Django web application, let's run it and see the effect! Open the browser and enter http://localhost:8000/myapp/. You will see a list of 5 recently published articles, all of which have been modified. As you hover over each article, their background color will change to pink, making them look prettier.

Conclusion

In this article, we covered how to create a beautiful web application using Python and Django. We started by installing Django, creating a new Django project, and creating a simple web application. We used Django's database model to define the Post object, and used Django's views and templates to present and query the data. Finally, we also added some styles and animations to the web application to make it look prettier.

Django is a powerful Python web application framework that helps us easily build beautiful, scalable web applications. If you're considering building your own web application using Python and Django, these tips should help you get started quickly.

The above is the detailed content of Django development: How to create a beautiful web application using Python and Django. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

See all articles