Creating a Python Django Website: A Beginner's Guide

Hey, are you dipping your toes into the world of web development? Or maybe you already have some experience but are looking for new tools? Today I'm going to talk to you about creating a website with Django in Python. Python Django is a powerful yet easy-to-learn web framework that is loved by many developers.

In this article, we'll take an honest look at the pros and cons of this combination, and we'll also walk you through how to install Python Django. We'll make it easy for beginners to follow along, so make sure to read on.

The compelling benefits of Python Django

There are so many advantages to creating a Python Django website.

  1. Battery inclusion philosophy: Django has a "battery included" philosophy, which means that the Most of the features you need for web development are already built inmeans. It comes with built-in admin pages, object-relational mapping (ORM), an authentication system, and more, greatly reducing development time.
  2. Python-basedBecause it's based on the Python language, it takes advantage of Python's concise and easy-to-read syntax. This makes it very accessible to beginners.
  3. Strong security: Django takes security seriously. It provides built-in protection against common security threats like SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF).
  4. Scalability: Django is great for building large websites. It has a structure that makes it easy to scale as your traffic grows.
  5. Active community: Many developers use Django, so it's easy to get help when you run into problems, and there are a variety of third-party packages that make it easy to extend functionality.

Python Django Cons: What you need to know

파이썬 장고 웹사이트 만들기 단점 요약 이미지
(Cons of creating a Python Django website)

However, there are some caveats to creating a Python Django website.

  1. Learning curveThe biggest downside is that there is a learning curve. As powerful as Django is, there are a lot of concepts to learn, and some of them can be a bit overwhelming, such as Model-View-Template (MVT) structures, ORMs, and middleware.
  2. Lack of flexibility: Django is a 'Conventions are better than settings' philosophy, it can sometimes feel inflexible, and many of the features Django offers can be overwhelming, especially for smaller projects.
  3. PerformanceBecause it's Python-based, it can be a bit slower to run than frameworks based on compiled languages. However, in most cases, this difference is not a big deal.
  4. Version compatibilityUpgrades should be done with caution, as major version updates to Django may break backwards compatibility.

Installing Python Django: Step by Step

Now let's see how to install Python Django.

  1. Install Python: First, you need to have Python installed. Python's official website (python.org)to download and install the latest version.
  2. Create a virtual environment (optional, but recommended): Use virtual environments to create independent environments for each project. Terminaland run the following command. A virtual environment named myenv will be created.
   python -m venv myenv

Then activate the virtual environment. For Windows and Mac/Linux operating systems, you can type in the terminal (command prompt) as shown below.

  • Windows: myenv\Scripts\activate
  • macOS/Linux: source myenv/bin/activate
  • 3. Install DjangoOpen a terminal (macOS, Linux) or command prompt (Windows) and enter the following command
   pip install django
  1. Verify installationOnce the installation is complete, you can verify that Django is installed properly with the following command
   python -m django --version

If a version number is printed, the installation completed successfully.

Create a Python Django website

Once you're done installing Python Django, it's time to create your first website.

  1. Create a projectTry running the following command in the terminal: : This will create a Django project named 'mysite'.
   django-admin startproject mysite
  1. Create an appYour Django project consists of several apps. Let's create our first app. In a terminal (or CMD window), navigate to the mysite folder and type the command create app.
   cd mysite
   python manage.py startapp myapp
  1. Change settings: mysite/settings.py Open the file and click INSTALLED_APPS Add 'myapp' to the list. This is something you should do by default whenever you create an app.
  2. Define a model: myapp/models.py file to define your data model. For example
   from django.db import models

   class Post(models.Model):
       title = models.CharField(max_length=200)
       content = models.TextField()
       created_at = models.DateTimeField(auto_now_add=True)

       def __str__(self):
           return self.title
  1. Migrating databasesThe first command detects the changes you've made to the model and creates a "blueprint" (migration file) to apply them to the database. The second reads the generated migration file and applies the changes to the actual database.
   python manage.py makemigrations
   python manage.py migrate
  1. Build a view: myapp/views.py Write a view in a file. Views are the "brains" of your Django application: they're responsible for receiving and processing requests from users and returning appropriate responses.
   from django.shortcuts import render
   from .models import Post

   def post_list(request):
       posts = Post.objects.all()
       return render(request, 'myapp/post_list.html', {'posts': posts})
  1. URL settings: mysite/urls.pyand myapp/urls.py Add the URL pattern to the file. Once you've built your view, you need to associate it with a URL. This is done by using the urls.py file. This will make sure that when you go to the '/posts/' URL, the post_list The view runs.
from django.urls import path
from . import views

urlpatterns = [
    path('posts/', views.post_list, name='post_list'),
]
  1. Create a template: myapp/templates/myapp/post_list.html file and write the HTML. The code below uses the myapp/templates/myapp/post_list.html You can save it to a file. This template creates a simple webpage that displays a list of posts.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Post List</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 0;
            background-color: #f4f4f9;
        }
        .container {
            width: 80%;
            margin: auto;
            overflow: hidden;
            padding: 20px;
            background: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .post {
            border-bottom: 1px solid #ddd;
            margin-bottom: 20px;
            padding-bottom: 10px;
        }
        .post:last-child {
            border-bottom: none;
        }
        .post-title {
            font-size: 1.5em;
            color: #333;
        }
        .post-content {
            font-size: 1em;
            color: #666;
        }
        .post-date {
            font-size: 0.8em;
            color: #999;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Post List</h1>
        {% if posts %}
            {% for post in posts %}
                <div class="post">
                    <h2 class="post-title">{{ post.title }}</h2>
                    <p class="post-content">{{ post.content }}</p>
                    <p class="post-date">Published on: {{ post.created_at }}</p>
                </div>
            {% endfor %}
        {% else %}
            <p>No posts available.</p>
        {% endif %}
    </div>
</body>
</html>
  1. Run the development server:
   python manage.py runserver

In your browser, go to http://127.0.0.1:8000/. If you see a screen like the one below, the Django server is up and running. Enter the address you set in the URL and you'll see that your first Django website is up and running.

파이썬 장고 웹사이트 만들기 - 서버 실행 이미지
(Create a Django Python website - Run the server )

Glossary of terms for beginners

  1. Web frameworksA web framework is a collection of tools that make it easy to create a website. Django is one such web framework.
  2. MTV PatternIt stands for Model (data management), Template (screen display), and View (logic processing) and refers to the way Django organizes your website.
  3. ORMOMR stands for Object-Relational Mapping, a technology that makes it easy to work with databases.
  4. Static web pages: A webpage that always shows the same thing.
  5. Dynamic web pages: A webpage that can show different content based on the user's request.
  6. Migration: Changes to the structure of the database. Django handles this automatically.
  7. Virtual EnvironmentsA technique to avoid package conflicts by creating independent Python environments for each project.

Closing thoughts: Open up a new world of web development with Python Django

Creating a website with Python Django can be challenging. But it's also a rewarding and exciting experience, and as you learn more about Django's powerful features, you'll be able to confidently create complex web applications.

Of course, it's important to weigh the pros and cons, and use it according to the size and nature of your project. For smaller projects, you might want to consider a lighter framework like Flask or FastAPI, but for scalability and maintainability, Python Django is a great choice.

We hope Python Django will be a great companion on your web development journey. Keep learning, keep experimenting, and keep building great websites. Don't give up if you get stuck. Every start is hard, but if you take it one step at a time, you'll get there. Good luck on your web development journey!

# Commentary - Model Definition Code Commentary

The code in the model definition part shows how Django defines the database tables. Let's go through each line one by one:
1. from django.db import models: Import the modules needed to use Django's model functionality.
2. class Post(models.Model):: Define a new model (table) called 'Post'. models.Modelto use Django's model functionality.
3. title = models.CharField(max_length=200): Create a field named 'title'. CharField is a string field that can store a title with a maximum length of 200 characters.
4. content = models.TextField()Create a field called : 'content'. A TextField is a field that can hold long pieces of text, making it perfect for storing the body content of a post.
5. created_at = models.DateTimeField(auto_now_add=True): Create a field named 'created_at'. A DateTimeField is a field that stores a date and time. auto_now_add=Truemeans that this field will automatically store the current date and time when it is first created.
6. def __str__(self):: This is a special method in Python, used to represent an object as a string.
7. return self.title: Tells this Post object to return the value of the title field when represented as a string. For example, when viewing this object on the admin page, the title will be displayed.
This defined model is then automatically converted into database tables by Django. This structure is then applied to the actual database through the migration process. This model makes it easy to manipulate the database with Python code.

#Further Comments - View Code Commentary

Let's take a closer look at this code line by line:
1. from django.shortcuts import render:
- Django's render Get the function.
- This function is used to load the template and generate HTML.
2. from .models import Post:
- The Post Import the model.
-. .modelsThe .means the current directory.
3. def post_list(request)::
-. post_listDefine a view function named
- All view functions take a request object, which contains information about the user's request.
4. posts = Post.objects.all():
- Get all Post objects from the database.
-. Post.objects.all()returns all instances of the Post model as a QuerySet.
5. return render(request, 'myapp/post_list.html', {'posts': posts}):
-. render function to generate an HTTP response.
- This function takes three arguments:
-. request: the current request object
-. 'myapp/post_list.html': Path to the template file to use
-. {'posts': posts}: Data to pass to the template (here we pass all Post objects with the name 'posts')

Similar Posts