Building a Django Blog and Vue Front-end with a GraphQL API: Everything You Need to Know
Are you interested in creating a robust web application that employs both a Django back-end and a Vue front-end? Look no further than this guide.
In this tutorial, we will be covering the building process of a Django blog with a Vue front-end and GraphQL API. The article will be organized in a step-by-step manner, making it easy to follow even for beginners.
Prerequisites
Before we get started, you should have basic knowledge of both Django and Vue. Additionally, it’s critical to have an understanding of reactive javascript, JSON, and Node.js.
Why Django and Vue?
When it comes to web development, Django, a Python-based framework, and Vue, a reactive javascript framework, are among the most commonly used technologies.
Django makes developing robust and complex web applications a simple task, while Vue allows developers to create interactive and responsive user interfaces. By combining the two, developers can produce top-tier web applications that solve many real-world problems.
What is GraphQL?
GraphQL is a query language that simplifies the process of fetching data from various APIs. It ensures that data requests are more efficient and does not require searching through unnecessary fields.
Moreover, it allows for strongly typed requests, which prevents the hard-coding of data types and provides more reliable type checking results.
Project Overview
The goal of this tutorial is to create a Django blog with a Vue front-end. We will be utilizing Django’s user authentication system to provide user registration and management features while also allowing users to create and edit posts within the blog.
We’ll use GraphQL to query the data and pass it between the front-end and back-end.
Step 1: Backend Set Up
To begin, we will set up Django’s back-end.
This will include creating a new Django project, installing the necessary packages, configuring the database, and creating a new Django app. After that, we will set up the Django authentication system and create models for the blog.
Step 2: Create GraphQL API
Next, we will create a GraphQL API that retrieves the information in the data model created in Step 1.
With GraphQL, we will be able to identify how we want the data structured and how best to retrieve data from the API.
We will create a URL endpoint to communicate with the API and test the GraphQL queries in the GraphiQL interface.
Step 3: Vue Front-End Set Up
Once the back-end is set up, we can set up the Vue front-end.
We’ll install the required Vue packages and create a new Vue app in the existing project. We will create new Vue components, import them into the main Vue file, and render the components on the page.
Step 4: Integrate Django and Vue
The final step is connecting the Vue front-end to the Django back-end using GraphQL. Since we’ve already set up the GraphQL API in Step 2, finding the API endpoint is straightforward.
We will use Apollo-Client to connect the two applications. Additionally, we will set up routes in Vue, allowing us to navigate between pages and access data from different API endpoints.
Conclusion
Overall, this tutorial can provide an excellent starting point for building a Django blog and Vue front-end with GraphQL API. Once the project is completed, you’ll have a solid foundation for creating full-stack web applications for your clients or for personal use.
As with all programming projects, there will be challenges, but the reward is a functioning application that you have created from start to finish.
Step 1: Set Up the Django Blog
Before we begin the project, let’s make sure that Django is installed and in the correct environment.
Creating a virtual environment is always a good practice as it separates the dependencies of each project and ensures that they don’t conflict with one another. Here are the steps to create a virtual environment:
- Open the terminal or command prompt and navigate to the desired directory where the project will live.
- Enter the following command:
python -m venv myenv
(replacemyenv
with a name of your choice). - Activate the virtual environment by running this command in the terminal:
.myenvScriptsactivate
(this command is for Windows. If you’re using a Mac, replace “myenv” with the virtual environment name). - Once the virtual environment is activated, we can install Django with
pip install Django
.
With that out of the way, let’s create the Django blog project:
- In the terminal, navigate to the directory where you want the project to live.
- Type
django-admin startproject myblog
, where “myblog” is the name of your project. - Open the project in your favorite text editor.
By following these commands, we have effectively created a new Django project.
Step 2: Create the Django Blog Admin
Having created the Django project, we need to create a Django app to manage the blog-specific functionality.
Using a separate app enhances the structure and maintainability of our codebase by conveniently grouping everything in a single directory.
- In the terminal, navigate to the project directory and type
python manage.py startapp blog
. This command creates a new app named “blog”. - Next, we need to add this app to our Django project.
- Let’s proceed to create data models that define our blog’s structure.
- It is still necessary to create the migration file.
- Finally, you can generate the database tables by running the
python manage.py migrate
command.
Open the myblog/settings.py
file, and search for the INSTALLED_APPS
tuple. Then, append 'blog'
within the parentheses.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
It will be helpful if we define these data models before we migrate them to the databases. Django comprises of many pre-built models that can be used directly or extended to implement custom behavior.
In our case, we will be using the User
model to handle authentication and authorization while creating a custom model to store blogs. Open the blog/models.py
file and add the following code:
from django.db import models
from django.contrib.auth.models import User
class Blog(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
published = models.DateTimeField(auto_now_add=True, editable=False)
updated = models.DateTimeField(auto_now=True, editable=False)
def __str__(self):
return self.title
In the above code, we define a Blog
model that has four fields: title
, content
, author
, and published
.
Additionally, we define two auto-updating fields, published
and updated
, that hold timestamps. The title
field is a CharField
with a maximum length of 200 characters.
The content
field is a TextField
. The author
field is a foreign key to the User
model and uses the on_delete=models.CASCADE
attribute to specify that if a user is deleted, all their posts will also be deleted.
A migration is used to initialize the database table structure for the new model. To do so, run the python manage.py makemigrations
command in the terminal.
Django will generate a migration file with instructions on how to create the database tables.
Conclusion
That’s it! We have created the Django blog admin to manage the blog-specific functionality. This comprised of setting up the blog app and creating data models.
In the next step, we’ll learn how to create a GraphQL API that retrieves information from our data model.
Step 3: Set Up Graphene-Django
In the previous step, we created a Django app for the blog-specific functionality.
In this step, we will integrate a GraphQL API using Graphene-Django.
Graphene-Django is a Python library that integrates seamlessly with Django to provide an easy way to implement GraphQL APIs. It provides a straightforward way to map Django models into GraphQL types and resolvers.
- To install Graphene-Django, run the following command in the terminal:
pip install graphene-django
- Next, we need to configure Graphene in our Django settings. Open the
myblog/settings.py
file and add the following to the bottom of the file: - We will create a new file in our
blog
app, namedschema.py
. - We also need to add a URL pattern to our Django project.
- Finally, in order to authenticate users in our GraphQL API, we can use
graphql-jwt
middleware, which works with JSON Web Token (JWT) authentication. First, run this command to installgraphql-jwt
:
GRAPHENE = {
'SCHEMA': 'blog.schema.schema',
'MIDDLEWARE': [
'graphql_jwt.middleware.JSONWebTokenMiddleware',
],
}
This code specifies where our GraphQL schema is located and adds the JSONWebTokenMiddleware
middleware for authentication.
This file will contain all the GraphQL configurations such as the schema, queries, mutations, and resolvers. Add the following code:
import graphene
from graphene_django import DjangoObjectType
from blog.models import Blog
class BlogType(DjangoObjectType):
class Meta:
model = Blog
class Query(graphene.ObjectType):
all_blogs = graphene.List(BlogType)
def resolve_all_blogs(self, info):
return Blog.objects.all()
schema = graphene.Schema(query=Query)
In the above code, we have created a BlogType
class that maps our Blog
model to a GraphQL type. Then, we have defined a Query
class that has a resolver method that retrieves all the blogs from the database and returns them.
Open the myblog/urls.py
file and add the following code:
from django.urls import path
from graphene_django.views import GraphQLView
urlpatterns = [
path('graphql', GraphQLView.as_view(graphiql=True)),
]
In this code, we have added a GraphQLView
that renders the GraphiQL interface when accessed at localhost:8000/graphql
.
pip install django-graphql-jwt
Then, add the following authentication configuration to your Django settings file:
GRAPHQL_JWT = {
'JWT_VERIFY_EXPIRATION': True,
'JWT_EXPIRATION_DELTA': timedelta(minutes=5),
'JWT_ALLOW_ARGUMENT': True,
}
With Graphene-Django integrated, we can now query our blog data from the front-end using GraphQL APIs.
Step 4: Set Up django-cors-headers
In modern web development, many web applications need to communicate with other web applications or web services. This can lead to a violation of the Same-Origin Policy, which forbids communication between different origins.
To enable cross-origin requests, we need to use django-cors-headers. django-cors-headers is a Django package that allows cross-origin requests from a specific domain by adding relevant headers.
- To install django-cors-headers, run the following command in the terminal:
pip install django-cors-headers
- Then, add
corsheaders
to yourINSTALLED_APPS
in your Django settings. - Add the
CorsMiddleware
to your middleware settings: - Finally, we need to specify which domains are allowed to access our web application.
- If you have CSRF (Cross-Site Request Forgery) protection enabled in your Django project, you will need to add the following line to your AJAX requests:
INSTALLED_APPS = [
...
'corsheaders',
... ]
MIDDLEWARE = [
... 'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
The order of the middleware is important. Make sure that 'corsheaders.middleware.CorsMiddleware'
is added before any middleware that might need to access the request
object.
In the Django settings file, add the following:
CORS_ALLOWED_ORIGINS = [
"http://localhost:8080",
]
This specifies that requests from http://localhost:8080
will be allowed.
headers: {
'X-CSRFToken': getCookie('csrftoken'),
}
The getCookie('csrftoken')
function retrieves the value of the CSRF token from the cookie.
Conclusion
In this tutorial, we covered two critical steps in setting up our Django blog with a Vue front-end and a GraphQL API. The first step involved integrating Graphene-Django to create a GraphQL API, and the second step involved installing and configuring django-cors-headers for cross-origin requests.
With these steps completed, we can now move on to the next step of setting up the Vue front-end of our application.
Step 5: Set Up Vue.js
In the previous steps, we created a Django project with GraphQL APIs. We will now set up the Vue.js front-end.
Vue.js is a reactive JavaScript framework that makes the creation of interactive and responsive user interfaces a breeze.
- To create a new Vue.js project, run the following command in the terminal:
vue create my-vue-app
. This command installs the Vue.js CLI and creates a new Vue project namedmy-vue-app
. - After creating the project, change the directory to
my-vue-app
and runnpm run serve
to start the development server. - We need to install a few plugins to our Vue project.
- Open the
App.vue
file in themy-vue-app/src
folder.
Run the following commands in the terminal:
npm install apollo-boost graphql graphql-tag vue-apollo --save
npm install bootstrap jquery popper.js --save
The above commands install the dependencies required for our project. vue-apollo
allows communication between our Vue front-end and the Django blog/GraphQL back-end, while bootstrap
, jquery
, and popper.js
are used to style the application.
In this file, we will import the required plugins and add the basic structure for the Vue front-end. Delete all the existing code and replace it with the following:
With the above code, we have added basic structure to the Vue.js front-end. We have provided the base HTML code for Vue.js to attach itself to, defined the JavaScript to implement GraphQL querying, and added the CSS styling.
Step 6: Set Up Vue Router
Now that we have set up Vue.js for our project, let’s add routing to our project. Vue Router is the official routing library for Vue.js.
- To install Vue Router, run the following command in the terminal:
npm install vue-router
- Create a new file
router.js
in thesrc
folder. In this file, we will add all the routing configurations for our Vue.js front-end. - In
main.js
, the main entry point of our Vue.js project, add the following code:
Add the following code:
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './components/Home.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'home',
component: Home,
},
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
export default router;
The above code specifies that the homepage of our project will be displayed by the Home
component.
import Vue from 'vue';
import App from './App.vue';
import router from './router';
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')
With the above code, we have specified that our Vue.js application should use the router for navigation, and which component to mount for the Vue.js app.
With this setup, we have configured the basic structure for both the Django back-end and Vue front-end.
The next step will be to create Vue components and integrate them with the Django back-end using GraphQL. This will involve making GraphQL queries to fetch data, handling user authentication, and creating forms for blog post creation and editing. This tutorial provided a basic overview, but it lays the foundation for creating a powerful, full-stack application using popular frameworks like Django and Vue.js.