Django + Angular 6 example | Django Rest Framework + MySQL CRUD example – Part 2: Django Server

django-angular-6-django-rest-api-mysql-angular-django-project-structure-feature-image

This tutorial is part 2 of Django-Angular-MySQL series. Today, we will create Django server to do CRUD with MySQL (including finder method).

>> Part 1: Overview
>> Part 3: Angular Client

Related Post:
Django RestApis example – GET/POST/PUT/DELETE requests MySQL database with Django REST Framework

Video

Django RestApi server Overview

Goal

Our Django Server can work with MySQL Database and provides APIs:

  • GET /customers/: get all customers
  • GET /customers/[id]: get a customer by id
  • GET /customers/age/[age]: find all customers by age
  • POST /customers/: save a customer
  • PUT /customers/[id]: update a customer by id
  • DELETE /customers/[id]: delete a customer by id
  • DELETE /customers/: delete all customers
Architecture

django-angular-6-django-rest-api-mysql-angular-server-architecture

Project structure

There are several folders and files in our Django project:

django-angular-6-django-rest-api-mysql-angular-django-project-structure

customers/apps.py: declares CustomersConfig class (subclass of the django.apps.AppConfig) that represents our Django app and its configuration.
gkzRestApi/settings.py: configures settings for the Django project, including INSTALLED_APPS list with Django REST framework and Customers Application.
customers/models.py: defines Customer data model class (subclass of the django.db.models.Model).
migrations/0001_initial.py: is generated by makemigrations command, includes the code to create the Customer model, will be run by migrate to generate MySQL database table for Customer model.
customers/serializers.py: declares CustomerSerializer class (subclass of rest_framework.serializers.ModelSerializer) for Customer instances to manage serialization to JSON and deserialization from JSON.
customers/views.py: contains methods to process HTTP requests and produce HTTP responses (using CustomerSerializer).
customers/urls.py: defines urlpatterns to be matched with request functions in the views.py.
gkzRestApi/urls.py: defines root URL configurations that includes the URL patterns declared in customers/urls.py.

Setup Django RestApi project

Install Django REST framework

Django REST framework works on top of Django and helps us to build RESTful Web Services flexibly. To install this package, run command:
pip install djangorestframework

Create RestApi project

Create Django project named gkzRestApi with command:
django-admin startproject gkzRestApi

django-angular-6-django-rest-api-mysql-angular-django-create-project

Install & Import Python MySQL Client

We have to install Python MySQL Client to work with MySQL database.
In this tutorial, we use pymysql: pip install pymysql.

Once the installation is successful, import this module in gkzRestApi/__init__.py:

import pymysql

pymysql.install_as_MySQLdb()
Setup MySQL Database engine

Open gkzRestApi/settings.py and change declaration of DATABASES:

DATABASES = {
   'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'testdb',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}
Create Customers App

Run following commands to create new Django App named customers:
cd gkzRestApi
python manage.py startapp customers

django-angular-6-django-rest-api-mysql-angular-django-create-project-app

Open customers/apps.py, we can see CustomersConfig class (subclass of the django.apps.AppConfig) that represents our Django app and its configuration:

from django.apps import AppConfig


class CustomersConfig(AppConfig):
    name = 'customers'
Add Django Rest framework & RestApi App to Django project

Open gkzRestApi/settings.py, find INSTALLED_APPS, then add:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Django REST framework 
    'rest_framework',
    # Customers application 
    'customers.apps.CustomersConfig',
]
Add CORS Configurations

Inside gkzRestApi/settings.py, add:

INSTALLED_APPS = [
    ...
    # CORS
    'corsheaders',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # CORS
    'corsheaders.middleware.CorsMiddleware',  
    'django.middleware.common.CommonMiddleware',  
]

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
    'localhost:4200',
)

Implement Django RestApi App

Data Model
Create Data Model

customers/models.py

from django.db import models


class Customer(models.Model):
    name = models.CharField(max_length=70, blank=False, default='')
    age = models.IntegerField(blank=False, default=1)
    active = models.BooleanField(default=False)
Run initial migration for data model

Run following Python script:
python manage.py makemigrations customers

We can see output text:

Migrations for 'customers':
  customers\migrations\0001_initial.py
    - Create model Customer

It indicates that the customers/migrations/0001_initial.py file includes code to create Customer data model:

# Generated by Django 2.1.7 on 2019-02-17 08:10

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Customer',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(default='', max_length=70)),
                ('age', models.IntegerField(default=1)),
                ('active', models.BooleanField(default=False)),
            ],
        ),
    ]

The generated code defines a subclass of the django.db.migrations.Migration. It has an operation for creating Customer model table. Call to migrations.CreateModel() method will create a table that allows the underlying database to persist the model.

Run the following Python script to apply the generated migration:
python manage.py migrate customers

The output text:

Operations to perform:
  Apply all migrations: customers
Running migrations:
  Applying customers.0001_initial... OK

Check MySQL Database, now we can see that a table for Customer model was generated and it’s named customers_customer:

django-angular-6-django-rest-api-mysql-angular-django-mysql-table

Create Serializer class

We need a Serializer class for Customer instances to manage serialization to JSON and deserialization from JSON.

– This CustomerSerializer will inherit from rest_framework.serializers.ModelSerializer superclass.
ModelSerializer class automatically populates a set of default fields and default validators, we only need to specify the model class.

Now, under customers package, create serializers.py file:

from rest_framework import serializers 
from customers.models import Customer


class CustomerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Customer
        fields = ('id',
                  'name',
                  'age',
                  'active')

Meta inner class declares 2 attributes:
model: specifies the model related to the serializer
fields: specifies a tuple of field names that we want to include in the serialization

Create API Views

Open customers/views.py file and declare two functions:
customer_list(): get list of customers, save a new customer, delete all customers
customer_detail(): get/update/delete customer by ‘id’
customer_list_age(): find all customers by ‘age’

from django.shortcuts import render 
from django.http import HttpResponse
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser 
from rest_framework import status

from customers.models import Customer
from customers.serializers import CustomerSerializer


@csrf_exempt
def customer_list(request):
    if request.method == 'GET':
        customers = Customer.objects.all()
        customers_serializer = CustomerSerializer(customers, many=True)
        return JsonResponse(customers_serializer.data, safe=False)
        # In order to serialize objects, we must set 'safe=False'

    elif request.method == 'POST':
        customer_data = JSONParser().parse(request)
        customer_serializer = CustomerSerializer(data=customer_data)
        if customer_serializer.is_valid():
            customer_serializer.save()
            return JsonResponse(customer_serializer.data, status=status.HTTP_201_CREATED) 
        return JsonResponse(customer_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    elif request.method == 'DELETE':
        Customer.objects.all().delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)


@csrf_exempt 
def customer_detail(request, pk):
    try: 
        customer = Customer.objects.get(pk=pk) 
    except Customer.DoesNotExist: 
        return HttpResponse(status=status.HTTP_404_NOT_FOUND) 
 
    if request.method == 'GET': 
        customer_serializer = CustomerSerializer(customer) 
        return JsonResponse(customer_serializer.data) 
 
    elif request.method == 'PUT': 
        customer_data = JSONParser().parse(request) 
        customer_serializer = CustomerSerializer(customer, data=customer_data) 
        if customer_serializer.is_valid(): 
            customer_serializer.save() 
            return JsonResponse(customer_serializer.data) 
        return JsonResponse(customer_serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
 
    elif request.method == 'DELETE': 
        customer.delete() 
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)

    
@csrf_exempt
def customer_list_age(request, age):
    customers = Customer.objects.filter(age=age)
        
    if request.method == 'GET': 
        customers_serializer = CustomerSerializer(customers, many=True)
        return JsonResponse(customers_serializer.data, safe=False)
        # In order to serialize objects, we must set 'safe=False'
Route Urls to Views functions

Create urls.py in customers folder, now we will define urlpatterns to be matched with request functions in the views.py.

from django.conf.urls import url 
from customers import views 
 
urlpatterns = [ 
    url(r'^customers/$', views.customer_list),
    url(r'^customers/(?P<pk>[0-9]+)$', views.customer_detail),
    url(r'^customers/age/(?P<age>[0-9]+)/$', views.customer_list_age),
]

Now we must include above URL patterns in root URL configurations.
Open gkzRestApi/urls.py, replace the code:

from django.conf.urls import url, include 
 
urlpatterns = [ 
    url(r'^', include('customers.urls')), 
]

Source Code

Django-RestApi-server-MySQL

36 thoughts on “Django + Angular 6 example | Django Rest Framework + MySQL CRUD example – Part 2: Django Server”

  1. Great beat ! I wish to apprentice while you amend your web site, how can i subscribe for a blog website?
    The account helped me a acceptable deal. I had been a little bit acquainted of
    this your broadcast provided bright clear idea

  2. I discovered your blog site on google and verify just a few of your early posts. Continue to keep up the very good operate. I simply additional up your RSS feed to my MSN Information Reader. Searching for ahead to studying extra from you afterward!?

  3. I was curious if you ever thought of changing the structure of your site? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or 2 pictures. Maybe you could space it out better?

  4. I believe that is one of the such a lot vital info for me. And i’m happy reading your article. However want to observation on few common things, The site style is wonderful, the articles is actually nice : D. Just right task, cheers

  5. Great beat ! I wish to apprentice even as you amend your site, how could i subscribe for a weblog web site? The account helped me a acceptable deal. I were a little bit familiar of this your broadcast offered shiny transparent idea

  6. Its like you learn my thoughts! You seem to know a lot approximately this, like you wrote the ebook in it or something. I feel that you can do with some to pressure the message home a little bit, however instead of that, this is excellent blog. An excellent read. I will certainly be back.

  7. Excellent read, I just passed this onto a colleague who was doing a little research on that. And he just bought me lunch because I found it for him smile Therefore let me rephrase that: Thanks for lunch!

  8. I and my guys happened to be viewing the best guides found on your web page then immediately got an awful suspicion I never expressed respect to the website owner for those secrets. The women are already for this reason very interested to read all of them and already have actually been loving those things. Many thanks for genuinely considerably helpful and for considering certain cool subjects millions of individuals are really desperate to be informed on. My sincere regret for not expressing gratitude to earlier.

  9. Good post here. One thing I’d like to say is the fact that most professional areas consider the Bachelor’s Degree just as the entry level requirement for an online education. Though Associate College diplomas are a great way to begin, completing a person’s Bachelors starts up many good opportunities to various jobs, there are numerous internet Bachelor Diploma Programs available by institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another thing is that many brick and mortar institutions provide Online editions of their qualifications but usually for a considerably higher price than the institutions that specialize in online diploma programs.

  10. Thanks for the advice on credit repair on this particular blog. The thing I would advice people would be to give up the particular mentality that they’ll buy currently and pay later. Being a society all of us tend to repeat this for many things. This includes vacations, furniture, in addition to items we really want to have. However, you need to separate your wants out of the needs. When you are working to boost your credit score you have to make some sacrifices. For example you can shop online to economize or you can go to second hand stores instead of expensive department stores regarding clothing.

  11. Interesting article. It is unfortunate that over the last years, the travel industry has already been able to to handle terrorism, SARS, tsunamis, bird flu, swine flu, and the first ever entire global economic collapse. Through everthing the industry has really proven to be effective, resilient in addition to dynamic, discovering new solutions to deal with hardship. There are always fresh complications and chance to which the business must once again adapt and answer.

  12. Thank you, I have just been looking for info about this topic for ages and yours is the greatest I’ve discovered so far. But, what about the bottom line? Are you positive in regards to the supply?

  13. Can I simply say what a reduction to search out somebody who actually is aware of what theyre speaking about on the internet. You positively know how one can carry a problem to light and make it important. More people have to read this and perceive this side of the story. I cant consider youre not more common because you definitely have the gift.

  14. You could definitely see your expertise in the paintings you write. The world hopes for even more passionate writers such as you who are not afraid to say how they believe. All the time follow your heart.

  15. Thanks for your submission. I would love to comment that the first thing you will need to complete is check if you really need fixing credit. To do that you simply must get your hands on a duplicate of your credit profile. That should not be difficult, considering that the government necessitates that you are allowed to acquire one free of charge copy of your credit report on a yearly basis. You just have to request that from the right people today. You can either look into the website owned by the Federal Trade Commission or even contact one of the major credit agencies right away.

  16. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three emails with the same comment. Is there any way you can remove me from that service? Bless you!

  17. magnificent points altogether, you simply gained a new reader. What would you suggest about your post that you made some days ago? Any positive?

  18. Unquestionably believe that which you stated. Your favorite justification seemed to be on the web the simplest thing to be aware of. I say to you, I certainly get irked while people think about worries that they plainly do not know about. You managed to hit the nail upon the top and also defined out the whole thing without having side-effects , people could take a signal. Will likely be back to get more. Thanks

  19. That is the fitting blog for anybody who wants to search out out about this topic. You realize a lot its almost laborious to argue with you (not that I really would want匟aHa). You positively put a new spin on a subject thats been written about for years. Great stuff, just great!

  20. Can I simply say what a reduction to find someone who actually is aware of what theyre speaking about on the internet. You positively know tips on how to convey a problem to gentle and make it important. More people need to learn this and perceive this aspect of the story. I cant believe youre not more well-liked because you definitely have the gift.

  21. 838405 458531Incredibly greatest man toasts, nicely toasts. is directed building your own by way with the wedding celebration as a result are supposed to try to be witty, amusing and consequently unusual as properly as. finest mans speech 686485

  22. It’s my belief that mesothelioma will be the most deadly cancer. It contains unusual features. The more I really look at it the harder I am convinced it does not work like a real solid tissues cancer. When mesothelioma is usually a rogue virus-like infection, hence there is the chance of developing a vaccine in addition to offering vaccination for asbestos open people who are at high risk connected with developing foreseeable future asbestos associated malignancies. Thanks for expressing your ideas for this important ailment.

  23. Great article and right to the point. I don’t know if this is in fact the best place to ask but do you folks have any ideea where to get some professional writers? Thanks in advance 🙂

  24. I would like to thnkx for the efforts you have put in writing this blog. I’m hoping the same high-grade web site post from you in the upcoming as well. In fact your creative writing abilities has encouraged me to get my own website now. Really the blogging is spreading its wings fast. Your write up is a great example of it.

Leave a Reply

Your email address will not be published. Required fields are marked *