GithubHelp home page GithubHelp logo

lead_manager_react_django's Introduction

Lead Manager

Full stack Django/React/Redux app that uses token based authentication with Knox.

Quick Start

# Install dependencies
npm install

# Serve API on localhost:8000
python leadmanager/manage.py runserver

# Run webpack (from root)
npm run dev

# Build for production
npm run build

lead_manager_react_django's People

Contributors

1shaked avatar bradtraversy avatar dependabot[bot] avatar dukarc avatar iurietarlev avatar mbb3-mitch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lead_manager_react_django's Issues

Support for Multiple PrivateRoutes

Hello,

I've added a second route to this project as my app needs multiple pages and paths, but it seems that when any page is refreshed is always redirects to the Dashboard.

Steps to reproduce:
First, add another PrivateRoute below the Dashboard. for example:
<PrivateRoute exact path="/" component={Dashboard} />
<PrivateRoute exact path="/pagetwo" component={PageTwo}/>

Then register, login, append "/pagetwo" to the URL, and refresh the page. The user ends up on "/" (the Dashboard) instead of "/pagetwo". Any ideas to support multiple PrivateRoutes?

Thanks!

What license is this code under?

Hey, thanks for the super useful guide and example code. I wanted to copy-paste some of this code into my own project as I'm doing basically exactly this.

I'm almost certain you don't care, but I'd like to have everything above board. So, could you please indicate what license this code is published under, so I and future contributors might use it without concern?

Production

I really need a guide or something for deploying this. Pleasee

Login error cannot read property 'data'

Hi,
I'm having some problems with frontend authentication.
I'm following all the steps from videos, and until now everything worked well. But now I have issues with login.
When I give invalid username/password I can see in redux extension 'LOGIN_FAIL' but when I log in with an actual account I don't see 'LOGIN_SUCCESS'. In console I see

Uncaught (in promise) TypeError: Cannot read property 'data' of undefined at eval (auth.js:54)

I tried to console.log(res) even console.log(res.data) everything looks fine. Why is that?
Here is my auth.js

import axios from 'axios';
import { returnErrors } from './messages';
import { USER_LOADED, USER_LOADING, AUTH_ERROR, LOGIN_SUCCESS, LOGIN_FAIL } from './types';

// Check token and load user
export const loadUser = () => (dispatch, getState) => {
    // User Loading
    dispatch({ type: USER_LOADING });

    // Get Token from state
    const token = getState().auth.token;

    // Headers
    const config = {
        headers: {
            "Content-Type": "application/json"
        }
    };

    // If token, add to headers
    if (token) {
        config.headers['Authorization'] = `Token ${token}`;
    }

    axios.get('/api/auth/user', config)
        .then(res => {
            dispatch({
                type: USER_LOADED,
                payload: res.data
            });
        }).catch(err => {
            dispatch(returnErrors(err.response.data, err.response.status));
            dispatch({
                type: AUTH_ERROR
            });
        });
};


// Login iser
export const login = (username, password) => dispatch => {
    // Headers
    const config = {
        headers: {
            "Content-Type": "application/json"
        }
    };

    // Request Body
    const body = JSON.stringify({ username, password });

    axios
        .post("/api/auth/login", body, config)
        .then(res => {
            dispatch({
                type: LOGIN_SUCCESS,
                payload: res.data
            });
        })
        .catch(err => {
            dispatch(returnErrors(err.response.data, err.response.status));
            dispatch({
                type: LOGIN_FAIL
            });
        });
};

I even have downloaded this code, I was checking all of this, even replacing with your code but I got the same error, maybe it's not a problem with auth.js?

Warning: Failed prop type: The prop `login` is marked as required in `Login`, but its value is `undefined`.

Hi.

I've been following the tutorial and encountered a problem. As the title says, browser by some reason can't find login function, though when building with npm run dev no errors appear.

actions/auth

import axios from "axios";
import {createMessage, returnErrors} from "./messages";
import { AUTH_ERROR, USER_LOADING, USER_LOADED, LOGIN_SUCCESS, LOGIN_FAIL } from "./types";


export const login = (username, password) => dispatch => {
    // Headers
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    };

    // Request Body
    const body = JSON.stringify({ username, password });

    axios.post('/users/login', body, config)
        .then(res => {
            dispatch(createMessage({ userLoggedIn: 'Successfully logged in'}));
            dispatch({
                type: LOGIN_SUCCESS,
                payload: res.data
            });
        }).catch(err => {
            dispatch(returnErrors(err.response.data, err.response.status));
            dispatch({
                type: LOGIN_FAIL
            });
    });
};

components/Login.js

import React, { Component } from 'react';
import { Link, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { login } from "../../actions/auth";


export class Login extends Component {
    state = {
        username: '',
        password: '',
    };

    static propTypes = {
        login: PropTypes.func.isRequired,
        isAuthenticated: PropTypes.bool
    };

    onChange = e => this.setState({ [e.target.name]: e.target.value });

    onSubmit = e => {
        e.preventDefault();
        console.log(this.props);
        this.props.login(this.state.username, this.state.password);
    };


    render() {
    ....
    }
}


const mapStateToProps = state => ({
    isAuthenticated: state.auth.isAuthenticated
});


export default connect(mapStateToProps, { login })(Login);

Tried to enter the page with both Firefox and Chrome - result the same. Am I missing something? Why it wouldn't run?

'AnonymousUser' object has no attribute 'leads'

In api.py of the leads app, in the function
def get_querysetself):
return self.request.user.leads.all()

Then I looked up and found that at the URL '/api/auth/login/', I'm not even getting a form in the API view of the rest framework. So I can't even post on the URL to login. Register is working, it creates users perfectly.
Problem is somewhere in LoginSerializer class.

When I visit '..../api/auth/login/' I get this without a post form.

GET /api/auth/login/
HTTP 401 Unauthorized
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept
WWW-Authenticate: Token

{
"detail": "Authentication credentials were not provided."
}

ModuleNotFoundError: No module named 'App Name' when using Django and Gunicorn on a heroku server

What I am trying to do here is setup a sample django app in heroku server. When running the app with gunicorn I get this error

This is what's in the log.

2020-02-14T12:11:30.549141+00:00 heroku[web.1]: State changed from crashed to starting 2020-02-14T12:11:41.607618+00:00 heroku[web.1]: Starting process with command gunicorn leadmanager.wsgi --log-file -`
2020-02-14T12:11:44.346394+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [4] [INFO] Starting gunicorn 20.0.4
2020-02-14T12:11:44.347348+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [4] [INFO] Listening at: http://0.0.0.0:54007 (4)
2020-02-14T12:11:44.347349+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [4] [INFO] Using worker: sync
2020-02-14T12:11:44.351554+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [10] [INFO] Booting worker with pid: 10
2020-02-14T12:11:44.359278+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [11] [INFO] Booting worker with pid: 11
2020-02-14T12:11:45.104994+00:00 heroku[web.1]: State changed from starting to crashed
2020-02-14T12:11:44.664943+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [11] [ERROR] Exception in worker process
2020-02-14T12:11:44.664951+00:00 app[web.1]: Traceback (most recent call last):
2020-02-14T12:11:44.664953+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2020-02-14T12:11:44.664953+00:00 app[web.1]: worker.init_process()
2020-02-14T12:11:44.664954+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process
2020-02-14T12:11:44.664954+00:00 app[web.1]: self.load_wsgi()
2020-02-14T12:11:44.664955+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi
2020-02-14T12:11:44.664955+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2020-02-14T12:11:44.664955+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
2020-02-14T12:11:44.664956+00:00 app[web.1]: self.callable = self.load()
2020-02-14T12:11:44.664956+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load
2020-02-14T12:11:44.664957+00:00 app[web.1]: return self.load_wsgiapp()
2020-02-14T12:11:44.664957+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp
2020-02-14T12:11:44.664957+00:00 app[web.1]: return util.import_app(self.app_uri)
2020-02-14T12:11:44.664958+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app
2020-02-14T12:11:44.664959+00:00 app[web.1]: mod = importlib.import_module(module)
2020-02-14T12:11:44.664959+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/importlib/init.py", line 127, in import_module
2020-02-14T12:11:44.664961+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2020-02-14T12:11:44.664961+00:00 app[web.1]: File "", line 1006, in _gcd_import
2020-02-14T12:11:44.664962+00:00 app[web.1]: File "", line 983, in _find_and_load
2020-02-14T12:11:44.664962+00:00 app[web.1]: File "", line 967, in _find_and_load_unlocked
2020-02-14T12:11:44.664962+00:00 app[web.1]: File "", line 677, in _load_unlocked
2020-02-14T12:11:44.664963+00:00 app[web.1]: File "", line 728, in exec_module
2020-02-14T12:11:44.664963+00:00 app[web.1]: File "", line 219, in _call_with_frames_removed
2020-02-14T12:11:44.664964+00:00 app[web.1]: File "/app/leadmanager/wsgi.py", line 16, in
2020-02-14T12:11:44.664964+00:00 app[web.1]: application = get_wsgi_application()
2020-02-14T12:11:44.664964+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
2020-02-14T12:11:44.664965+00:00 app[web.1]: django.setup(set_prefix=False)
2020-02-14T12:11:44.664965+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/init.py", line 24, in setup
2020-02-14T12:11:44.664966+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS)
2020-02-14T12:11:44.664966+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate
2020-02-14T12:11:44.664966+00:00 app[web.1]: app_config = AppConfig.create(entry)
2020-02-14T12:11:44.664967+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/config.py", line 90, in create
2020-02-14T12:11:44.664967+00:00 app[web.1]: module = import_module(entry)
2020-02-14T12:11:44.664967+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/importlib/init.py", line 127, in import_module
2020-02-14T12:11:44.664968+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2020-02-14T12:11:44.664968+00:00 app[web.1]: File "", line 1006, in _gcd_import
2020-02-14T12:11:44.664969+00:00 app[web.1]: File "", line 983, in _find_and_load
2020-02-14T12:11:44.664969+00:00 app[web.1]: File "", line 965, in _find_and_load_unlocked
2020-02-14T12:11:44.664970+00:00 app[web.1]: ModuleNotFoundError: No module named 'leads'

In the settings.py I am including the apps like this

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'whitenoise.runserver_nostatic', 'rest_framework', 'leads', 'frontend', 'knox', 'accounts' ]

Below is my folder structure
TzcBj

I am new to django
Please help as I have found no solution for this with my limited knowledge and hours of browsing

Using BrowserRouter instead of HashRouter

Any problems associated with a HashRouter vs BrowserRouter like you used in this tutorial? In the react-router documentations it recommends making the server compatible with BrowserHistory over HashHistory. I was able to get this working by using re_path(r'^(?:.*)/?$', include('frontend.urls')) at the end of urlpatterns in the leads.urls. This way index.html is always loaded by default if the URL doesn't match anything else. I am curious if this is worth doing or if HashRouter is the way to go.

requirements.txt

Can you run code below for the other people (especially for those using virtualenv) can quick start the project?

pip freeze requirements.txt

Clear leads on logout

/src/reducers/leads.js

case LOGOUT_SUCCESS:
return {
...state,
leads: [] <- back to an empty array otherwise the leads remain in redux on logout
};

Unable to delete lead

When I click delete button this erros pops up on the console!

developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
xhr.js:178 GET http://127.0.0.1:8000/api/leads/$(id)/ 404 (Not Found)
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios.<computed> @ Axios.js:76
wrap @ bind.js:9
eval @ leads.js:25
eval @ index.js:9
dispatch @ VM649:1
eval @ redux.js:485
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306
executeDispatch @ react-dom.development.js:389
executeDispatchesInOrder @ react-dom.development.js:414
executeDispatchesAndRelease @ react-dom.development.js:3278
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287
forEachAccumulated @ react-dom.development.js:3259
runEventsInBatch @ react-dom.development.js:3304
runExtractedPluginEventsInBatch @ react-dom.development.js:3514
handleTopLevel @ react-dom.development.js:3558
batchedEventUpdates$1 @ react-dom.development.js:21871
batchedEventUpdates @ react-dom.development.js:795
dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568
attemptToDispatchEvent @ react-dom.development.js:4267
dispatchEvent @ react-dom.development.js:4189
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
discreteUpdates$1 @ react-dom.development.js:21887
discreteUpdates @ react-dom.development.js:806
dispatchDiscreteEvent @ react-dom.development.js:4168

leads.js:31 Error: Request failed with status code 404
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:61)

production build - 404 error static/frontend/main.js not found

Hi,

Thanks for the setup. So far it's been pretty much everything I was looking for. However I was testing this for a production environment but I'm getting an error after running npm run build
GET http://localhost:8000/static/frontend/main.js [HTTP/1.1 404 Not Found 4ms]
The resource from “http://localhost:8000/static/frontend/main.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).

I'm not sure if the second line is related.
Have there been any other issues with this? As far as I can tell it should source the same main.js webpack as it does when running dev.

my django static settings are simple
STATIC_URL = '/static'
Any insight would be greatly appreciated!

Successful Login but its not Redirecting

Hi, I'm already at the part 7 of the video tutorial, and I was able to Login but it's not redirecting to the dashboard.

import React, { Component } from 'react';
import { Link, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { login } from "../../actions/auth";

export class Login extends Component {
state = {
username:"",
password:""
};

static propTypes = {
    login: PropTypes.func.isRequired,
    isAutheticated: PropTypes.bool
};

onSubmit = e => {
    e.preventDefault();
    this.props.login(this.state.username, this.state.password);
};

onChange = e => this.setState({ [e.target.name]: e.target.value });

render() {
    if(this.props.isAutheticated) {
        return <Redirect to="/" />;
    }
    const { username, password } = this.state;
    return (
        <div className ="col-md-6-m-auto">
            <div className="card card-body mt-5">
                <h2 className="text-center">Login</h2>
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label>Username</label>
                        <input type="text" className="form-control"
                        name="username"
                        onChange={this.onChange}
                        value={username} />
                    </div>
                    <div className="form-group">
                        <label>Password</label>
                        <input type="password" className="form-control"
                        name="password"
                        onChange={this.onChange}
                        value={password} />
                    </div>
                    <div className="form-group">
                        <button type="submit" className="btn btn-primary">Login</button>
                    </div>
                    <p>
                        Don't have an account? <Link to="/register">Register</Link>
                    </p>
                </form>
            </div>
        </div>
    );
}

}

const mapStateToProps = state => ({
isAutheticated: state.auth.isAutheticated
});

export default connect(mapStateToProps, { login })(Login);
Capture2

Getting "Unexpected Token" error on a fresh clone

Get an issue on my machine when I try to run this by itself. Followed steps in readme

e.g. Steps are

  1. git clone https://github.com/bradtraversy/lead_manager_react_django.git
  2. cd lead_manager_react_django
  3. npm install
  4. pipenv shell
  5. pipenv install
  6. python leadmanager/manage.py runserver
  7. open new git bash window and goto the leads project folder
  8. run "npm run dev"

ERROR
`\lead_manager_react_django\leadmanager\frontend\src\components\App.js: Unexpected token (37:6)

35 | render() {
> 36 | return (
37 | <Provider store={store}>
| ---^
38 | <AlertProvider template={AlertTemplate} {...alertOptions}>
39 |
40 |
`

System and Tools

  • Windows 10
  • Using Git Bash

Please let me know if I can provide any more details

Leads not showing after adding them

I am on the last tutorial but whenever I add a lead, I get an alert that says lead added but the leads do not show up! Has anyone else had that problem?
I have no spelling or extra "s" errors.

403 Error

I still get a 403 error even after following your code.
Screenshot 2022-08-23 at 00 01 34

Routing not working properly

Redirecting after login isn't working properly.
I can see errors in log.

Edit:
It was caused by django version.
For routing, path is used in django 2.x, url is used in django 1.x.

Webpack issue

Hi there Brad, Thank you for your great tutorial, I get an error when I run the "npm run build" command.

Error:

webpack is watching the files…

Insufficient number of arguments or no entry found.
Alternatively, run 'webpack(-cli) --help' for usage info.

Hash: 1a8ae2f3f9b1fc0393e9
Version: webpack 4.39.3
Time: 49ms
Built at: 09/07/2019 11:51:57 PM

ERROR in Entry module not found: Error: Can't resolve 'babel-loader' in '/Users/apple/My_project/NewDJ'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.