A simple app using Django with REST + MySQL + Webpack + Vue.js
- Init project & run development server:
# Ref: https://docs.djangoproject.com/en/2.1/intro/tutorial01/
# Init project
django-admin startproject djangosample
# Migrate Django app
python3 manage.py migrate
# Try running development server
python3 manage.py runserver
- Create Django app:
# Create Django app
python3 manage.py startapp invoice
# Create model
# https://docs.djangoproject.com/en/2.0/topics/db/models/
# Make migration
python3 manage.py makemigrations
# Migrate
python3 manage.py migrate
- Install Django-rest-framework
# Ref: http://www.django-rest-framework.org/
pip3 install djangorestframework
- Create Serializer, Viewset and Routers
Then check in browser: http://127.0.0.1:8000/invoice
- Install VueJs with webpack template
# Install in frontend folder
vue init webpack frontend
# Confirm installation finished:
cd frontend && npm run dev
# then access http://127.0.0.1:8080 in browser
- Enabling CORS on Django
pip3 install django-cors-headers
- Add to
your_project/settings.py
:
INSTALLED_APPS = [
# ...
'corsheaders',
]
MIDDLEWARE = [
# ...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
CORS_ORIGIN_WHITELIST = (
'localhost:8080',
'127.0.0.1:8080',
)
- Make a sample REST API:
- Add below code to
invoice/views
:
from rest_framework.decorators import api_view
from django.http import HttpResponse
def sayHello(request):
return HttpResponse("Hello")
- Add below code to
your_project/urls
:
from django.conf.urls import url
from invoice import views
urlpatterns = [
url(r'^api/say_hello/', views.sayHello),
]
- Make sample interface in Vue:
- Install
axios
:
cd frontend && npm install --save axios
- Create file
./frontend/src/model/ModelService.js
:
import axios from 'axios'
export default class ModelService {
sayHello () {
return axios.get('http://localhost:8000/api/public/', {headers: {}}).then((response) => {
return response.data || 'default value'
})
}
}
-
Create sample home page: Check
App.vue
file -
Confirm:
python manage.py runserver
cd frontend
# run Vue.js in another terminal tab
npm run dev
Ref: