top of page
Writer's picturevP

Day 25 - Introduction to Django - Web Development in Python

Welcome back to the #PythonForDevOps series. Today, on Day 25, we are taking a deep dive into the fascinating world of web development with Python, and our guide for this journey is Django.


What is Django?

Django is a high-level web framework written in Python that encourages rapid development and clean, pragmatic design. It follows the Model-View-Controller (MVC) architectural pattern, allowing developers to build robust web applications with ease.


Let's break down what each part of MVC means:

  • Model: Represents the data structure and business logic of the application.

  • View: Handles the presentation and user interface of the application.

  • Controller: Manages the communication between the Model and the View.

In simpler terms, Django helps you organize your code and build web applications in a structured way.


Why Django?

Before we jump into the hands-on part, you might be wondering why you should choose Django for web development. Well, here are a few compelling reasons:


Batteries-Included Philosophy: Django comes with a wide range of built-in features and tools, saving you from the hassle of searching for third-party libraries. This includes an admin panel, authentication system, and more.


Documentation: Django boasts extensive and well-maintained documentation. Whether you're a beginner or an experienced developer, you'll find answers to your questions easily.


Scalability: Django is scalable, making it suitable for both small projects and large, complex applications. It grows with your needs.


Security: Django takes security seriously. It helps developers avoid common security mistakes and provides tools to protect against various types of attacks.


Now that we know why Django is a fantastic choice, let's get our hands dirty with some code.


Installing Django

First things first, let's install Django. Open your terminal and run the following command:

pip install django

Once the installation is complete, let's create a new Django project. Run the following command, replacing "myproject" with the name you want for your project:

django-admin startproject myproject

This creates a new directory with the project structure. Navigate into the project directory:

cd myproject

Your First Django App

Now that our project is set up, let's create a Django app. An app is a self-contained module that does something specific. In our case, it could be a blog, a forum, or any other feature of your web application.

Run the following command to create an app (replace "myapp" with your desired app name):

python manage.py startapp myapp

Now, let's define a simple model for our app. Open the models.py file inside the myapp directory and define a model like this:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()

    def str(self):
        return self.title

This model represents a basic blog post with a title and content.


Migrating the Database

Django uses migrations to handle database schema changes. Run the following commands to apply the initial migration and create the database tables:

python manage.py makemigrations
python manage.py migrate

Creating an Admin Panel

One of the cool things about Django is the built-in admin panel. Register your Post model in the admin.py file inside the myapp directory:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Now, run the development server:

python manage.py runserver

Visit http://127.0.0.1:8000/admin/ in your browser and log in using the admin credentials. You'll see the Post model ready for you to add, edit, and delete posts.


Views and Templates

Django uses views to handle web requests and templates to render HTML. Open the views.py file in the myapp directory and define a simple view:

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})

Create a templates directory inside the myapp directory and add a new file named post_list.html with the following content:

{% for post in posts %}
  <h2>{{ post.title }}</h2>
  <p>{{ post.content }}</p>
{% endfor %}

Now, let's connect this view to a URL. Open the urls.py file in the myapp directory and define a URL pattern:

from django.urls import path
from .views import post_list

urlpatterns = [
    path('posts/', post_list, name='post_list'),
]

Include these URLs in the project's urls.py:

from django.contrib import admin
from django.urls import include, path
urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.urls')),
]

Run the development server again and visit http://127.0.0.1:8000/myapp/posts/ in your browser. You should see a list of your blog posts.


Congratulations! You've just scratched the surface of Django web development. This powerful framework empowers you to build robust, scalable web applications with ease. Explore the Django documentation to delve deeper into its features and possibilities.


Stay tuned, and happy coding!


*** Explore | Share | Grow ***

3 views0 comments

Comentários

Avaliado com 0 de 5 estrelas.
Ainda sem avaliações

Adicione uma avaliação
bottom of page