Introduction to Python Django Basics: A Demo Project featuring Models and Full CRUD Operations

Posted by

Python Django Basics – Demo Project with Models and Full CRUD

Python Django Basics – Demo Project with Models and Full CRUD

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It’s great for building web applications quickly and efficiently. In this article, we’ll walk you through the basics of Django by creating a demo project with models and full CRUD functionality.

Setting up Django Project

First, make sure you have Django installed. You can do this by running the following command:

$ pip install django

Once Django is installed, you can create a new Django project by running the following command:

$ django-admin startproject myproject
$ cd myproject

Creating Models

Models in Django are used to define the structure of your database tables. Let’s create a simple model for our demo project:

# models.py

from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name

After defining the model, you need to create migrations and apply them to your database. This can be done by running the following commands:

$ python manage.py makemigrations
$ python manage.py migrate

Creating Views and Templates

Next, we need to create views and templates for our CRUD operations. Let’s create views for creating, reading, updating, and deleting items:

# views.py

from django.shortcuts import render, redirect
from .models import Item

def item_list(request):
    items = Item.objects.all()
    return render(request, 'item_list.html', {'items': items})

Now, create templates for displaying the item list and item details:

{% extends 'base.html' %}

{% block content %}
    

Item List

{% for item in items %}

{{ item.name }}

{{ item.description }}

{% endfor %} {% endblock %}

Full CRUD Functionality

To implement full CRUD functionality, you need to create views and templates for creating, updating, and deleting items. Here’s an example of a create view:

#views.py

def create_item(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        description = request.POST.get('description')
        Item.objects.create(name=name, description=description)
        return redirect('item_list')
    return render(request, 'create_item.html')

And the corresponding template:

{% extends 'base.html' %}

{% block content %}
    

Create Item

{% csrf_token %}

{% endblock %}

Conclusion

In this article, we’ve covered the basics of Django by creating a demo project with models and full CRUD functionality. We’ve created models, views, and templates to implement a simple CRUD application. Django is a powerful framework that can help you build web applications quickly and efficiently. We hope this article has helped you get started with Django!