Skip to content

A Django and React Template that will help you skip a lot of boilerplate and initial project setup

License

Notifications You must be signed in to change notification settings

Terkea/django_react_template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

A Django & React Template

All Contributors

A Django and React Template that will help you skip a lot of boilerplate and initial project setup, which features:

  • Passwordless user authentification/registration, which is a more modern and secure way of logging in, used by Medium, Microsoft and plenty more.
  • Functionality to update the user profile.
  • Responsiveness

This template is based on the Ant Design ui kit and is powered by the Django REST Framework.

login login login

Motivation

When starting a new project it can be incredibly time consuming to reach the milestone that will finally let you start implementing your ideas, and doing actual work.

The goal of this project is to be just that, a solid modern project template that you can easily pick up on and not worry too much about the boilerplate.

DISCLAIMER

Please bear in mind that this is a development version, for production you would ideally have to change a lot of settings and it is recommended that you go through them yourself and check what needs to be changed to make it safe for production deployment.

Installation

Option 1

> Docker

To install it with docker, you only need to run the following command:

# Make sure that you have Docker installed, use -d to hide logs
docker-compose up --build

You can access it through localhost:3000 by default.

To Remove the containers use:

docker-compose down

Option 2

> React

cd react
# Install the node packages
npm install
# Start the App in Development Mode
npm start

> Django

cd django
# Create the virtual environment
python -m venv env 
# You need to activate everytime you open a new terminal
./env/Scripts/activate
# Install the requirements
pip install -r requirements.txt 
python manage.py makemigrations
python manage.py migrate
# In case django complains about migrations at any point go with
python manage.py migrate --run-syncdb
# Run the server
python manage.py runserver

You can access it through localhost:3000 by default.

Documentation

> React

Introduction

This documentation will assume a fair knowledge of React as well as some of the tools that we are used, including:

Updating the Base URL

To change the Base URL all that you have to do is change it inside the file axiosConfig.js.

const instance = axios.create({
    baseURL: 'http://localhost:8000'
});

Routes

The App.js component (App.js) is being used as the main router and it is here that the main routes are defined. If you want to define other routes in your sub-components, you should not use <Router> again.

As an example of this you can take the My Profile page, where a Switch component is used:

MyProfile

<Switch>
    <Route exact path={`${basicPATH}`} component={BasicSettings} />
    <Route exact path={`${securityPATH}`} component={SecuritySettings} />
</Switch>

As you may have noticed the path is not a literal string, this is so that it can accomodate for any future path changes, you can implement this with the following code:

// ...
// inside the component
const getUrl = () => {
    // This function can be used to reliably get the current url with 1 slash at the end
    const inconsistentUrl = props.match.url;
    const lastUrlChar = inconsistentUrl[inconsistentUrl.length - 1];
    return ((lastUrlChar === '/') ? inconsistentUrl : (inconsistentUrl + '/'));
}

const url = getUrl();
//paths: 
const basicPATH = `${url}basic/`;
const securityPATH = `${url}security/`
// ...

Note: Unfortunately the getUrl can not be made into a helper function, at least for now.

Customization - Antd Theming

antd theming ANTD is using Less as the development language for styling. A set of less variables are defined for each design aspect that can be customized to your needs. There are some major variables below, all less variables could be found in Default Variables.

Your custom changes should go in react/config-overrides.js.

For all of the potential customizations don't hesitate to check their documentation which covers them all.

Layout Component

Layout Component (Layout.js)

In this template the layout component is to be used to display the main content of the webpage.

Navbar

  • When logged out:

    navbar1

  • When logged in:

    navbar2

To add more links you can just add more Menu.Item under Menu and make sure that the Link to is the same as the Menu.Item key without the / at the end, otherwise it won't show as selected, you can look at how this was done for the existing ones.

Tip: make sure that the Menu.Item is not nested in any other component and that it goes right under Menu.

Sessions

The session is managed by the Redux store.

When the page is loaded, an action actions.authCheckState() is dispatched, from App.js, to the store actions which just checks for the existence of a token in localStorage and if there is no token in localStorage it logs the user out, otherwise it checks the token's validity and dispatches some other actions check authCheckState() to see the code.

When the user is not logged in the store looks the following:

user store

When the user is logged in the store looks the following:

user store

Note: To visualize the above you need to get the Redux DevTools Extension.

  • user
    • loading - is a boolean that can used, for example, in the conditional rendering of elements, this is used in Login and My Profile.
    • error - is a boolen, that can be used, for example, to set a given element to show that it errored out, such as an icon.
    • email - note that email is moved inside profile once the user has logged in.

Login / Register

Login (Login.js) / Register (App.js)

Both of these do exactly the same thing, they sign in the user whether they are registered or not, the reason why a registration page exists is to not confuse users that may be looking for the common register/login pages.

My Profile

My Profile (MyProfile/index.js)

More options will be added in the future, these existing ones are just a proof of concept or example.

Notifications

Notifications (notificationHelpers.js)

The current notification system is based on the Ant Design notifications and it is implemented as a callback for actions that are dispatched to the store, this callback is optional but it is currently the way to run a notification when the axios request returns its promise.

A good example of how to use these notifications can be seen in Basic.js.

Basic.js

import { runNotifications } from '../../../Helpers/notificationHelpers';
// ...
// Inside the component:
    const onFinish = values => {
        props.updateProfile(localStorage.getItem('token'), values, runNotifications)
    };
// ...
const mapDispatchToProps = dispatch => {
    return {    // map the callback just like a regular argument, in whatever action you want to dispatch
        updateProfile: (token, profile, callback) => dispatch(actions.updateProfile(token, profile, callback))
    }
}
// ...

user.js

// ...
// when you define your action make sure to define an empty anonymous function as the
// default function in case you don't want to call notifications on the given action
export const updateProfile = (token, profile, notificationCallback = (message, outcome) => { }) => dispatch => {
    // ...
    // axios request
        .then(res => {
            // ...
            notificationCallback("Profile Updated Successfully", "SUCCESS");
        })
        .catch(err => {
            // ...
            notificationCallback(err.message, "ERROR");
        })
}
// ...

How to add dependencies for Docker

TODO

> Django

Django user model

Custom fields can be appended to the default userprofile model that we provided by editing the model itself and the serializer. which can be located in django/api/models/ and `django/api/serializers/

Configuring the SMTP Server

Update the following constants to get your smtp server up and running

# SMTP SETTINGS
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
PASSWORDLESS_AUTH = {
    'PASSWORDLESS_AUTH_TYPES': ['EMAIL'],
    'PASSWORDLESS_EMAIL_NOREPLY_ADDRESS': "your.email@email.com",
}

Then be sure you change from backends console to smtp

# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

Contributors ✨

Thanks goes to these wonderful people (emoji key):


AName* name("Vadim");

⚠️ πŸ“– 🚧 πŸ‘€ βœ… πŸ’»

Marian Terchila

⚠️ πŸ“– 🚧 πŸ‘€ βœ… πŸ’»

This project follows the all-contributors specification. Contributions of any kind welcome!