Django REST API & ReactIf you would like to use Django as the back-end and React as the front-end, you have to install and set up the REST API. The Django framework has a straightforward solution, which is popular among the developer community. Let me show you how to implement it step by step.
If you don't have a Django project and an app for this purpose, you should create a new one. In my example, it will be the project of a todo app.
According to this, we are starting by creating some folders for our apps!
Open your command-line interface or shell!
Select your project folder!
$ mkdir todo
$ cd todo
$ mkdir backend
$ cd backend
Create a Django project!
If you have not seen the 'Hello world app' chapter yet, click on this link.
$ python manage.py startapp todos
$ python manage.py migrate
Migrating your initial database.
Create models to your todo databse!
$ python manage.py migrate todos
Migrating your todo models to database.
Create superuser!
$ python manage.py createsuperuser
After this command you have to add your username, email and password on the command-line.
With using this account you can update your database and add new todo for instance.
Log in to your admin interface and add todos: http://localhost:8000/admin/
Use 'Add +' button and fill the text fields (title, body)!
$ pipenv install djangorestframework
Add 'rest_framework' to the INSTALLED_APPS in your settings.py file!
Add AllowAny to your settings.py file!
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
}
Set up your urls.py file!
Create serializers.py file!
With serializers we can transfrom data from Django-models to JSON.
Add the next classes to your views.py file!
$ pipenv install django-cors-headers
With CORS (Cross-Origin Resource Sharing) we can specify which cross-domain requests should be permitted.
Your settings file should look like this now. I highlighted which part is updated.
$ python manage.py runserver
Run this on your browser: http://localhost:8000/api/
You have to get something like this:
Open a new command-line console and keep open the other for the todo-api!
Two console are open now. One for backend (port:8000) and one for frontend (port:3000).
Install node if you have not done yet!
Check this: Development environment with Node
$ npm install axios
$ npm start
Change src/Apps.js content for the next snippet!
Run build command on the folder that includes the react app.
$ npm run build
Run this on your browser: http://localhost:3000