Django CRUD Application with VueJs as front-end | VueJs + Django Rest Framework + MySQL example – Part 2: Django Server

django-vue-crud-example-django-rest-api-mysql-feature-image

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

>> Part 1: Overview
>> Part 3: VueJs Client

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

Video

[coming soon…]

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[0-9]+)$', views.customer_detail),
    url(r'^customers/age/(?P[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'^api/', include('customers.urls')), 
]

Source Code

Django-RestApi-server-MySQL

73 thoughts on “Django CRUD Application with VueJs as front-end | VueJs + Django Rest Framework + MySQL example – Part 2: Django Server”

  1. It’s the best time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions. Maybe you could write next articles referring to this article. I desire to read even more things about it!

  2. Hello there! I know this is kinda off topic but I was wondering if you
    knew where I could get a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having trouble finding one?
    Thanks a lot!

  3. 997632 639994Excellently written post, doubts all bloggers offered the same content because you, the internet can be a greater place. Please keep it up! 296198

  4. I do believe all of the ideas you’ve introduced in your post. They’re really convincing and can certainly work. Nonetheless, the posts are very short for starters. Could you please extend them a bit from next time? Thank you for the post.

  5. The Zune concentrates on getting a Moveable Media Player. Not a web browser. Not a video game machine. Quite possibly in just the future it’ll do even far better within just people areas, nonetheless for at this time it is really a exceptional way in the direction of set up and pay attention in direction of your songs and flicks, and is without the need of peer inside that regard. The iPod’s positive aspects are its net going to and apps. If people solid more persuasive, perhaps it is your ideal determination.

  6. 991860 621084This web internet site is genuinely a walk-through for all with the info you wanted about this and didnt know who to ask. Glimpse here, and youll definitely discover it. 923859

  7. I carry on listening to the news bulletin speak about getting boundless online grant applications so I have been looking around for the top site to get one. Could you advise me please, where could i acquire some?

  8. I’ve been surfing online more than three hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. Personally, if all web owners and bloggers made good content as you did, the web will be much more useful than ever before.

  9. Hello, Neat post. There is a problem together with your site in web explorer, could test this… IE nonetheless is the marketplace chief and a huge component of other people will leave out your magnificent writing because of this problem.

  10. It’s appropriate time to make some plans for the future and it is time to be happy. I have read this put up and if I could I desire to recommend you some interesting issues or suggestions. Maybe you can write next articles referring to this article. I wish to read even more issues about it!

  11. Hi, Neat post. There’s a problem with your website in internet explorer, would check this… IE still is the market leader and a large portion of people will miss your fantastic writing due to this problem.

  12. I have been exploring for a bit for any high quality articles or blog posts on this sort of house . Exploring in Yahoo I eventually stumbled upon this web site. Studying this info So i¦m satisfied to exhibit that I have an incredibly excellent uncanny feeling I came upon just what I needed. I such a lot indisputably will make certain to don¦t omit this web site and provides it a glance regularly.

  13. The crux of your writing whilst sounding reasonable at first, did not sit properly with me after some time. Someplace within the sentences you actually were able to make me a believer unfortunately just for a very short while. I however have a problem with your jumps in logic and one would do well to help fill in all those gaps. In the event that you actually can accomplish that, I will undoubtedly be fascinated.

  14. Heya i am for the first time here. I found this board and I in finding It truly useful & it helped me out a lot. I’m hoping to present something back and help others like you aided me.

  15. I think this is among the most significant info for me. And i’m glad reading your article. But want to remark on some general things, The site style is ideal, the articles is really great : D. Good job, cheers

  16. I’m not certain the place you are getting your information, however good topic. I needs to spend a while studying more or figuring out more. Thank you for wonderful information I used to be in search of this info for my mission.

  17. F*ckin’ remarkable things here. I am very satisfied to look your post. Thanks so much and i am looking forward to contact you. Will you please drop me a e-mail?

  18. Hello very nice site!! Guy .. Excellent .. Wonderful .. I will bookmark your blog and take the feeds also…I’m happy to seek out so many helpful information right here within the post, we need work out more strategies in this regard, thanks for sharing.

  19. I would like to thnkx for the efforts you have put in writing this blog. I am hoping the same high-grade blog post from you in the upcoming as well. In fact your creative writing abilities has inspired me to get my own blog now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.

  20. Hey very nice website!! Man .. Excellent .. Amazing .. I’ll bookmark your website and take the feeds also…I am happy to find a lot of useful info here in the post, we need work out more techniques in this regard, thanks for sharing. . . . . .

  21. Thanks for the sensible critique. Me and my neighbor were just preparing to do a little research about this. We got a grab a book from our area library but I think I learned more from this post. I’m very glad to see such fantastic information being shared freely out there.

  22. We are a group of volunteers and starting a new scheme in our community. Your web site offered us with valuable information to work on. You have done an impressive job and our entire community will be grateful to you.

  23. 442612 279185When do you think this Real Estate market will go back in a positive direction? Or is it still too early to tell? We are seeing a lot of housing foreclosures in Altamonte Springs Florida. What about you? Would really like to get your feedback on this. 29458

  24. Heya i’m for the first time here. I came across this board and I find It truly useful & it helped me out a lot. I hope to give something back and help others like you helped me.

  25. It is appropriate time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I wish to suggest you some interesting things or advice. Maybe you could write next articles referring to this article. I desire to read even more things about it!

  26. Great goods from you, man. I have bear in mind your stuff prior to and you are just too excellent. I really like what you have acquired right here, really like what you are stating and the best way through which you assert it. You make it entertaining and you continue to care for to keep it sensible. I can’t wait to read far more from you. That is actually a terrific website.

  27. Pretty part of content. I just stumbled upon your blog and in accession capital to say that I acquire in fact loved account your blog posts. Anyway I’ll be subscribing in your augment or even I fulfillment you get entry to constantly fast.

  28. I like what you guys are up too. Such smart work and reporting! Carry on the excellent works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my website 🙂

  29. A lot of thanks for your entire labor on this web site. Kim really likes getting into investigations and it’s really easy to understand why. Almost all notice all regarding the compelling means you produce great things on the blog and even encourage response from visitors on that issue then my child is really starting to learn a lot of things. Have fun with the remaining portion of the new year. You are always conducting a good job.

  30. Simply wish to say your article is as astonishing. The clearness to your submit is simply great and that i can assume you are a professional in this subject. Well together with your permission allow me to grasp your feed to stay up to date with imminent post. Thank you one million and please continue the gratifying work.

  31. Thanks for a marvelous posting! I truly enjoyed reading it, you can be a great author.I will ensure that I bookmark your blog and will eventually come back down the road. I want to encourage yourself to continue your great work, have a nice holiday weekend!

  32. Hi, I think your site might be having browser compatibility issues. When I look at your website in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, fantastic blog!

Leave a Reply

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