Django introduction

Introduction:

Django, a high-level Python web framework, has gained immense popularity for its simplicity, versatility, and scalability. Whether you're a novice developer or someone with experience in other languages, Django provides an excellent starting point for building robust web applications. This blog post will guide you through the basics of Django, helping you take your first steps into the world of web development.


What is Django?

Django is an open-source web framework written in Python. It follows the Model-View-Controller (MVC) architectural pattern, but in Django's terminology, it's referred to as the Model-View-Template (MVT). This framework encourages rapid development, clean and pragmatic design, and the "Don't Repeat Yourself" (DRY) principle.


Prerequisites:

Before diving into Django, ensure  the following installed on the system:

Python: Django is a Python framework, so having Python installed is essential. We can download the latest version from Python's official website.


Pip: Pip is a package installer for Python. You can check if you have Pip installed by running pip --version. If not, you can install it by following the official instructions.


Installing Django

After Python and Pip installed, we can install Django using the following command:

pip install django

Creating the First Django Project

To create a simple Django project. Open  terminal and run the following commands:

django-admin startproject myproject

cd myproject

This creates a new directory named myproject with the basic structure of a Django project.


Understanding the Structure:

A Django project consists of several components:


manage.py: A command-line utility that lets us interact with our project in various ways.


myproject/: The project's main directory containing settings, URLs, and other configurations.


myapp/: A sample application within the project. In a larger project, you might have multiple apps.


Creating a Django App:

Django projects are composed of one or more apps. Let's create a simple app:

python manage.py startapp myapp

This command generates a directory named myapp with the necessary files and folders.


Defining Models:

In Django, a model is a Python class that defines the structure of a database table. Open the models.py file in your myapp directory and define a simple model:


from django.db import models


class Item(models.Model):

    name = models.CharField(max_length=100)

    description = models.TextField()


    def __str__(self):

        return self.name

This model represents an Item with a name and description.


Creating Migrations:

Django uses migrations to manage database schema changes. Run the following commands to create and apply migrations:


python manage.py makemigrations

python manage.py migrate

These commands will create an SQLite database and apply the model changes.


Creating an Admin Panel:

Django provides a built-in admin panel for managing data. To use it, register your model in the admin.py file:

from django.contrib import admin

from .models import Item

admin.site.register(Item)

Now,  run the development server:


python manage.py runserver

Visit http://127.0.0.1:8000/admin/ in the browser, log in using the admin credentials, and we can see the Item model listed.


Creating Views and Templates:

Django follows the MVT pattern, where the template is responsible for the presentation logic. Let's create a simple view and template.


In views.py:

from django.shortcuts import render

from .models import Item


def item_list(request):

    items = Item.objects.all()

    return render(request, 'myapp/item_list.html', {'items': items})

Create a folder named templates within your myapp directory. Inside templates, create a file named item_list.html:


<!DOCTYPE html>

<html>

<head>

    <title>Item List</title>

</head>

<body>

    <h1>Item List</h1>

    <ul>

        {% for item in items %}

            <li>{{ item.name }} - {{ item.description }}</li>

        {% endfor %}

    </ul>

</body>

</html>

Now, define a URL for theview. In the myapp directory, create a file named 

urls.py:

from django.urls import path

from .views import item_list


urlpatterns = [

    path('items/', item_list, name='item_list'),

]

Include this URL configuration in the project's urls.py:


from django.contrib import admin

from django.urls import include, path


urlpatterns = [

    path('admin/', admin.site.urls),

    path('', include('myapp.urls')),

]

Now, when we run your development server and visit http://127.0.0.1:8000/items/, we can see the list of items.

Comments

Popular posts from this blog

Python program to sum up the Salary when the Name and Age matches with subsequent rows.

Automation using selenium and python/java interview question to order a product in e commerce website.