Building a contacts manager using Vue.js and Django as the backend - part two

Building a contacts manager using Vue.js and Django as the backend - part two

Published 10. oct 2019 07:21 by Stein Ove Helset

In the second part of the "Building a contacts manager using Vue.js and Django as the backend" tutorial we're going to go through how to get the Django backend ready.

First of all, weelcome back to the second part of this Vue.js and Django tutorial! If you haven't completed part one yet, you should do it now.

The first thing you can do is to open up your command line and go in to the root of the Django project. Once you're there, you can run these two commands:

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

This will create the initial database and make sure everything is ready. Next, we're going to the a Django app for the contacts. This app will contain a database model, serializers for the API and views. To create the app, run the following command:

$ python manage.py startapp contact

We also need to add 'contact' to the INSTALLED_APPS in settings.py. So just go ahead and add it to the list just like you did with 'corsheaders' and 'rest_framework' in the previous part. The reason we have to do this is because our Django project wouldn't know the app existed if it wasn't in that list. INSTALLED_APPS should look like this now:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'rest_framework',
    'contact'
]

Creating the database model

Django knows there is an app now, but we need to tell Django what kind of data it should store and how. Inside the 'contact' folder, open up 'models.py' in your editor and write the following:

from django.db import models

class Contact(models.Model):
        name = models.CharField(max_length=255)
        phone = models.CharField(max_length=255, blank=True, null=True)
        email = models.CharField(max_length=255, blank=True, null=True)

        class Meta:
                ordering = ('name',)

        def __str__(self):
                return self.name

On the first line, we import models from Django. We create a new class called Contact which is the actual model. For this app we only need three fields: name, phone and email. We add a new property to the Meta sub class so that when we get contacts from the database, it's ordered alphabetically by name.

Once again we need to tell the database that there's new tables to create. Run the two following commands:

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

Adding some demo content

Before we continue, let's add a couple of contacts using the command line. Open up a Django shell by running this command:

$ python manage.py shell

When the shell has opened, you can type these four commands:

>>> from contact.models import Contact
>>> c1 = Contact.objects.create(name='John Doe', phone='+123 321 123', email='john@doe.com')
>>> c2 = Contact.objects.create(name='Jane Doe', phone='+123 321 123', email='jane@doe.com')
>>> Contact.objects.all()

Now we've created two contacts (John Doe and Jane Doe). The last command pulls all contacts from the database and prints them in a list.

Django Rest Framework Serializers

First of all, what is a serializer? A serializer is a class/method used by Django to get data from the database and present it in a way an API can understand. Create a new file inside the 'contact' folder called 'serializers.py'. Type the following code inside:

from rest_framework import serializers

from .models import Contact

class ContactSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Contact
        fields = ('id', 'name', 'phone', 'email')

This is pretty basic Django/Python syntax. We create a serializer based on the "Contact" model and we want to get those four exact fields.

The views

We also need to create a view. This view will get the serialized data and use a predefined (from Django) ViewSet to return a http response. 'contact/views.py' should look like this:

from .models import Contact # Import our Contact model
from .serializers import ContactSerializer # Import the serializer we just created

# Import django rest framework functions

from rest_framework import viewsets  # Import a function for creating views

class ContactViewSet(viewsets.ModelViewSet): # Create a class based view
    """
    API endpoint that allows tasks to be viewed or edited.
    """
    queryset = Contact.objects.all() # Select all contacts
    serializer_class = ContactSerializer # Serialize data

Django URLS

The last step we have to do before we can test is to add the view in Django's router. Open up 'djangocontacts/urls.py' and change it to look like this:

from django.contrib import admin
from django.urls import path, include

from rest_framework import routers # Import the router

from contact.views import ContactViewSet # Import the view we just created

router = routers.DefaultRouter() # Define the router with our view
router.register(r'contacts', ContactViewSet)

urlpatterns = [
        path('', include(router.urls)), # Add the view to the patterns
]

Try the API using curl

Open up a commandline and type the following command:

$ curl -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/contacts/
[
    {
        "id": 2,
        "name": "Jane Doe",
        "phone": "+123 321 123",
        "email": "jane@doe.com"
    },
    {
        "id": 1,
        "name": "John Doe",
        "phone": "+123 321 123",
        "email": "john@doe.com"
    }
]

Nice, right? As you can see, this is the two contacts we added earlier in this part of the tutorial

That was it for this part of the tutorial. Stay tuned for the next part where we go through how to consume the API using Axios and present it in the Vue.js frontend.

Buy me a coffee

Buy me a coffeeBuy me a coffee

Share this post

Comments

Add comment