Building a CRUD application using Python and Django

Introduction:

I’ve been meaning to write a series on Django which is a web application framework written in Python. To follow this tutorial you don’t need to be a pro in python and have to know it inside-out. Just some basics will get you through it.

Before we start writing applications, we must know a little about what is Django. Django is a web application framework that acts more of an MTV pattern instead of MVC. Think it this way:

  • Model remains model

  • View has been replaced by Templates

  • Controller gets replaced by View

A simple Hello-world application is just a few lines of code in Django! But moving from this simple thing a full fledged application can be a daunting task in itself. There are other concepts that can help proceed further such as ORM, migrations etc that help in building a bigger application. But for this tutorial we’ll be building a simple CRUD( Create, Retrieve, Update and Delete ) application.

To get started with you need to have python and virtualenv installed on your machine. Python is already installed on the linux systems. But you'll need to install virtualenv. To install virtualenv follow the command:

sudo apt-get install python-pip
sudo pip install virtualenv

Application Structure

Before we actually start writing code we need to get a hold of the application structure. We'll first execute several commands that are essential in django project development.

After installing virtualenv, we need to set the environment up.

virtualenv venv

We are setting a virtual environment of the name venv here. Now we need to activate it.

source venv/bin/activate
cd venv

Now that it has been activated. We need to start our project. Feed in the following command to start a project.

pip install django==1.11.8
mkdir app && cd app
django-admin startproject crudapp

The first line installs Django v1.11.8 and creates a directory named app in the parent directory. the third line starts a project named crudapp in the app directory. The directory tree should look like

app
└── crudapp
    ├── crudapp
    │   ├── __init__.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    └── manage.py

We'll see the meaning of each file and what it does one by one. But first, to test if you are going in the right directoion, run the following command.

python manage.py runserver

If you get an output like below then you're doing it right.

Let's see what exactly the different files that we created mean.

  • __init__.py : Acts as an entry point for your python project.

  • settings.py : Describes the configuration of your Django installation and lets Django know which settings are available.

  • urls.py : used to route and map URLs to their views.

  • wsgi.py : contains the configuration for the Web Server Gateway Interface. The Web Server Gateway Interface (WSGI) is the Python platform standard for the deployment of web servers and applications.

Writing the Application

Now this is where we start coding our app. For this operation we'll consider blog post as our entity. We'll be applying CRUD operations to blog posts.

The app in our project will be called blog_posts.

python manage.py startapp blog_posts

This will create the necessary files that we require.

First and foremost create the Model of our application.

# -*- coding: utf-8 -*-
	from __future__ import unicode_literals
from django.db import models


# Create your models here.
class blog_posts(models.Model):
    title = models.CharField(max_length=400)
    tag = models.CharField(max_length=50)
    author = models.CharField(max_length=120)


    def __unicode__(self):
        return self.title


    def get_post_url(self):
        return reverse('post_edit', kwargs={'pk': self.pk})

Now that we have our model ready, we’ll need to migrate it to the database.

python manage.py makemigrations
python manage.py migrate

Now we create our Views where we define each of our CRUD definition.

# -- coding: utf-8 --
from future import unicode_literals

from django.shortcuts import render, redirect, get_object_or_404
from django.forms import ModelForm


from blog_posts.models import blog_posts
# Create your views here.


class PostsForm(ModelForm):
    class Meta:
        model = blog_posts
        fields = ['id', 'title', 'author']


def post_list(request, template_name='blog_posts/post_list.html'):
    posts = blog_posts.objects.all()
    data = {}
    data['object_list'] = posts
    return render(request, template_name, data)


def post_create(request, template_name='blog_posts/post_form.html'):
    form = PostsForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('blog_posts:post_list')
    return render(request, template_name, {'form': form})


def post_update(request, pk, template_name='blog_posts/post_form.html'):
    post = get_object_or_404(blog_posts, pk=pk)
    form = PostsForm(request.POST or None, instance=post)
    if form.is_valid():
        form.save()
        return redirect('blog_posts:post_list')
    return render(request, template_name, {'form': form})


def post_delete(request, pk, template_name='blog_posts/post_delete.html'):
    post = get_object_or_404(blog_posts, pk=pk)
    if request.method=='POST':
        post.delete()
        return redirect('blog_posts:post_list')
    return render(request, template_name, {'object': post})

Now that we have our Views, we create mappings to URL in our /crudapp/blog_posts/urls.py file. Make a note that the following is our app specific mappings.

“”"
crudapp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
"""
from django.conf.urls import url
from django.contrib import admin
from blog_posts import views


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.post_list, name='post_list'),
    url(r'^new$', views.post_create, name='post_new'),
    url(r'^edit/(?P<pk>\d+)$', views.post_update, name='post_edit'),
    url(r'^delete/(?P<pk>\d+)$', views.post_delete, name='post_delete'),
]

Now we create project specific mappings in /crudapp/crudapp/urls.py.

“”"
Crudapp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
     https://docs.djangoproject.com/en/1.11/topics/http/urls/
 """
from django.conf.urls import url, include
from django.contrib import admin
from crudapp.views import home


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^blog_posts/', include('blog_posts.urls', namespace='blog_posts')),
    url(r'^$', home, name='home' ),
]

Now almost everything is done and all we need to do is create our templates to test the operations.

Go ahead and create a templates/blog_posts directory in crudapp/blog_posts/.

  • templates/blog_posts/post_list.html:
<!DOCTYPE html>
<html>
<head>
<meta charset=“utf-8”>
<link rel=“stylesheet” href=“https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css”>
<title>Django CRUD application!</title>
</head>
<body>
<div class=“container”>
<h1>Blog Post List!</h1>
<ul>
{% for post in object_list %}
<li><p>Post ID: <a href=“{% url “blog_posts:post_edit” post.id %}”>{{ post.id }}</a></p>
<p>Title: {{ post.title }}</p>
<a href=“{% url “blog_posts:post_delete” post.id %}”>Delete</a>
</li>
{% endfor %}
</ul>

    &lt;a href="{% url "blog_posts:post_new" %}"&gt;New Blog post entry&lt;/a&gt;
&lt;/div&gt;

</body>
</html>

templates/blogposts/postform.html

<!DOCTYPE html>
<html>
<head>
<meta charset=“utf-8”>
<link rel=“stylesheet” href=“https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css”>
<title>Django CRUD application!</title>
</head>
<body>
<div class=“container”>
<form method=“post”>{% csrf_token %}
{{ form.as_p }}
<input class=“btn btn-primary” type=“submit” value=“Submit” />
</form>
</div>
</body>
</html>

templates/blogposts/postdelete.html

<!DOCTYPE html>
<html>
<head>
<meta charset=“utf-8”>
<link rel=“stylesheet” href=“https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css”>
<title>Django CRUD application!</title>
</head>
<body>
<div class=“container”>
<form method=“post”>{% csrf_token %}
Are you sure you want to delete “{{ object }}” ?
<input class=“btn btn-primary” type=“submit” value=“Submit” />
</form>
</div>
</body>
</html>

Now we have all the necessary files and code that we require.

The final project tree should look like following:

crudapp
├── blog_posts
│   ├── admin.py
│   ├── apps.py
│   ├── init.py
│   ├── migrations
│   ├── models.py
│   ├── templates
│   │   └── blog_posts
│   │   ├── post_delete.html
│   │   ├── post_form.html
│   │   └── post_list.html
│   ├── tests.py
│   ├── urls.py
│   ├── views.py
├── crudapp
│   ├── init.py
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   ├── wsgi.py
├── db.sqlite3
├── manage.py
└── requirements.txt

Execute python manage.py runserver and voila!! You have your Django app ready.

Originally published by  Nitin Prakash at  zeolearn.com

===================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Python for Time Series Data Analysis

☞ Python Programming For Beginners From Scratch

☞ Python Network Programming | Network Apps & Hacking Tools

☞ Intro To SQLite Databases for Python Programming

☞ Ethical Hacking With Python, JavaScript and Kali Linux

☞ Beginner’s guide on Python: Learn python from scratch! (New)

☞ Python for Beginners: Complete Python Programming



#python #django

What is GEEK

Buddha Community

Building a CRUD application using Python and Django
Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

7 Mistakes You Should Avoid While Building a Django Application

Django…We all know the popularity of this Python framework. Django has become the first choice of developers to build their web applications. It is a free and open-source Python framework. Django can easily solve a lot of common development challenges. It allows you to build flexible and well-structured web applications.

A lot of common features of Django such as a built-in admin panel, ORM (object-relational mapping tool), Routing, templating have made the task easier for developers. They do not require spending so much time on implementing these things from scratch.

One of the most killer features of Django is the built-in Admin panel. With this feature, you can configure a lot of things such as an access control list, row-level permissions, and actions, filters, orders, widgets, forms, extra URL helpers, etc.

Django ORM works with all major databases out of the box. It supports all the major SQL queries which you can use in your application. Templating engine of Django is also very, very flexible and powerful at the same time. Even a lot of features are available in Django, developers still make a lot of mistakes while building an application. In this blog, we will discuss some common mistakes which you should avoid while building a Django application.

#gblog #python #python django #building a django application #django #applications

Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Sival Alethea

Sival Alethea

1624418760

Weather App - Django Tutorial (Using Python Requests). DO NOT MISS!!!

See how to create a weather app in Django that gets the current weathers for multiple cities. This tutorial uses Python Requests to call the Open Weather Map API.

📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=qCQGV7F7CUc&list=PLWKjhJtqVAbnqBxcdjVGgT3uVR10bzTEB&index=15
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#weather app #django #python #weather app - django tutorial (using python requests) #using python requests #django tutorial

Ahebwe  Oscar

Ahebwe Oscar

1620177818

Django admin full Customization step by step

Welcome to my blog , hey everyone in this article you learn how to customize the Django app and view in the article you will know how to register  and unregister  models from the admin view how to add filtering how to add a custom input field, and a button that triggers an action on all objects and even how to change the look of your app and page using the Django suit package let’s get started.

Database

Custom Titles of Django Admin

Exclude in Django Admin

Fields in Django Admin

#django #create super user django #customize django admin dashboard #django admin #django admin custom field display #django admin customization #django admin full customization #django admin interface #django admin register all models #django customization