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.
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.
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.
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.
docker-compose down
cd react
# Install the node packages
npm install
# Start the App in Development Mode
npm start
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.
This documentation will assume a fair knowledge of React as well as some of the tools that we are used, including:
- Ant Design as the UI webkit.
- React Hooks
- React Redux
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'
});
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.
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.js)
In this template the layout component is to be used to display the main content of the webpage.
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 underMenu
.
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:
When the user is logged in the store looks the following:
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 (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 (MyProfile/index.js)
More options will be added in the future, these existing ones are just a proof of concept or example.
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
.
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))
}
}
// ...
// ...
// 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");
})
}
// ...
TODO
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/
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': "[email protected]",
}
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'
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!