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

You ought to absolutely look at Django. It is written in Python and Python is astounding, spotless, simple to learn, and one of the most shown programming dialects. Python is additionally a well known decision for:

Modern Light and Magic (Star Wars special visualizations)

Game turn of events

Administrations like Pinterest, Instagram, The Guardian and then some

Beyond question, the tech market is flooded with systems, however Django is a decent spot to begin as it has the most delightful documentation and instructional exercises in programming advancement. Presently, for the principle fascination – the benefits and detriments of utilizing Django. 
Django classes in pune

Django Course in pune

Django Training  in pune

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

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

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