Can't Get Angular To Load Routes

Issue

I am making a local page following this tutorial, and it implements a login using django and angular. But I can’t get the button register to show anything. It just changes the directory to /register. I think it has to do with routing. I get no errors. And I don’t know how to debug this thing anymore, so I’ve run out of options. This is my first ‘website’.

Reason this isn’t going smooth is because I did not get the starter project the tutorial came with. I wanted to learn how to implement this from scratch. This means my packages are newer (bootstrap, django, etc). Let me know if you need any more info, please. Thanks.

/templates/index.html

<!DOCTYPE html>
<html ng-app="hawk">

<head>
  <title>Hawk</title>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>

<body>
  {% include 'navbar.html' %}

  <div class="container-fluid">
    <div class="row">
      <div class="col-xs-12 ng-view"></div>
    </div>
  </div>

  {% include 'javascripts.html' %}
</body>

</html>

/static/javascripts/hawk.routes.js

(function () {
    'use strict';

    angular
        .module('hawk.routes')
        .config(config);

    config.$inject = ['$routeProvider'];

    function config($routeProvider) {
        $routeProvider.when('/register', {
            controller: 'RegisterController',
            controllerAs: 'vm',
            templateUrl: '/static/templates/authentication/register.html'
        }).otherwise('/');
    }
})();

/static/javascripts/authentication/controllers/register.controller.js

(function () {
    'use strict';

    angular
        .module('hawk.authentication.controllers')
        .controller('RegisterController', RegisterController);

    RegisterController.$inject = ['$location', '$scope', 'Authentication'];

    function RegisterController($location, $scope, Authentication) {
        var vm = this;
        console.log("\n\nregister\n\n");
        vm.register = register;

        function register() {
            Authentication.register(vm.email, vm.password, vm.username);
        }
    }
})();

/static/javascripts/hawk.js

(function () {
  'use strict';

  angular
    .module('hawk', [
      'hawk.routes',
      'hawk.authentication',
      'hawk.config',
    ]);

  angular
    .module('hawk.routes', [require('angular-route')]);
  angular
    .module('hawk.config', []);
  angular
    .module('hawk')
    .run(run);
  run.$inject = ['$http'];

  function run($http) {
    $http.defaults.xsrfHeaderName = 'X-CSRFToken';
    $http.defaults.xsrfCookieName = 'csrftoken';
  }
})();

/templates/javascripts.html

{% load compress %} {% load staticfiles %} {% compress js %}
<script type="text/javascript" src="{% static '../node_modules/jquery/dist/jquery.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/bootstrap/dist/js/bootstrap.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/bootstrap-material-design/dist/js/material.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/bootstrap-material-design/js/ripples.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/underscore/underscore.js' %}"></script>

<script type="text/javascript" src="{% static '../node_modules/angular/angular.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/angular-route/angular-route.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/angular-cookies/angular-cookies.js' %}"></script>

<script type="text/javascript" src="{% static '../node_modules/ng-dialog/js/ngDialog.js' %}"></script>
<script type="text/javascript" src="{% static 'lib/snackbarjs/snackbar.min.js' %}"></script>

<script type="text/javascript" src="{% static 'javascripts/hawk.js' %}"></script>

<script type="text/javascript" src="{% static 'javascripts/hawk.config.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/hawk.routes.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/authentication/authentication.module.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/authentication/services/authentication.service.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/authentication/controllers/register.controller.js' %}"></script> 
{% endcompress %}

/static/javascripts/authentication/services/authentication.service.js

(function () {
    'use strict';
    angular
        .module('hawk.authentication.services')
        .factory('Authentication', Authentication);
    Authentication.$inject = ['$cookies', '$http'];

    function Authentication($cookies, $http) {
        var Authentication = {
            register: register
        };

        return Authentication;

        function register(email, password, username) {
            return $http.post('/api/v1/accounts/', {
                username: username,
                password: password,
                email: email
            });
        }
    }
})();

/HawkProject/urls.py

from django.contrib import admin
from django.urls import path, re_path, include
from rest_framework_nested import routers
from authentication.views import AccountViewSet
from HawkProject.views import IndexView

router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^api/v1/', include(router.urls)),

    re_path(r'^.*$', IndexView.as_view(), name='index')
]

Solution

Although its not an answer to this question precisely but its an answer with a diff approach

The tutorial you have provided is too long and not included with video. I have worked on Django and AngularJS to create an ecommerce website. I’l suggest you not to mix Django and AngularJS as much as you can to avoid conflicts. That being said, I’ll provide you what I implemented for User Registration in brief:

  1. I kept User form separate from AngularJS forms because Django has its own way to handle User Management (Sign in,sign Up, session (using @login_required) etc).

  2. I provided <a href="/sign_up">Register</a> on the nav-bar. (Note: /signup is a url mapped in urls.py file)

        <form name="regForm" class="form-signup" action="/sign_up/" method="post" role="form" onsubmit="return validateForm()">
            {% csrf_token %}
            {{form.errors.values.0}}
            <div class="form-group reg-username" id="fname">
                <div>
                    <input name="first_name" class="form-control input" size="20" placeholder="Enter First Name" type="text" required>
                </div>
                <p id="fname-error" class="help-block"></p>
            </div>
            <div class="form-group reg-username">
                <div>
                    <input name="last_name" class="form-control input" size="20" placeholder="Enter Last Name" type="text" required>
                </div>
            </div>
            <div class="form-group reg-email">
                <div>
                    <input name="email" class="form-control input" placeholder="Enter Email" type="email" required>
                </div>
            </div>
            <div class="form-group reg-password" id="pwd1">
                <div>
                    <input name="password1" class="form-control input" placeholder="Password" type="password" required>
                </div>
                <p id="pwd-error1" class="help-block"></p>
            </div>
            <div class="form-group reg-password" id="pwd2">
                <div>
                    <input name="password2" class="form-control input" placeholder="Confirm Password" type="password" required>
                </div>
                <p id="pwd-error2" class="help-block"></p>
            </div>
            <input name="submit" class="btn  btn-block btn-lg btn-primary" value="REGISTER" type="submit">
    
        </form>
    

Where url(r'^sign_up/', ('ecommerce.views.register_user')),

In the views.py

@sensitive_post_parameters()
@csrf_protect
@requires_csrf_token
def register_user(request):
    args = {}
    args.update(csrf(request))
    if request.method == 'POST':

        if not verify_google_recaptcha(request.POST):
            return HttpResponse(get_status_response('Failure', 'Are you sure you are not a robot?'))
        else:
            logger.info('Recaptcha passed !!!')

        form = RegistrationForm(request.POST)
        msg = 'register'
        args['form'] = form

        if form.is_valid():

            try:
                # username = form.cleaned_data['username']
                email_obj ={}
                email_obj['email'] = form.cleaned_data['email']
                email_obj['first_name'] = form.cleaned_data['first_name']
                email_obj['last_name'] = form.cleaned_data['last_name']

                salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
                activation_key = hashlib.sha1(salt + email_obj['email']).hexdigest()

                email_obj['activation_link'] = ACTIVATION_LINK.format(activation_key)

                template = get_template('RegistrationLink.html')
                context = Context({'email': email_obj})
                content = template.render(context)

                emsg = EmailMultiAlternatives('Activation link for {0}'.format(DEFAULT_DOMAIN) , content, DEFAULT_FROM_EMAIL, to=[email_obj['email']])

                emsg.attach_alternative(content, "text/html")
                emsg.send()

                form.save()  # save user to database if form is valid

                # Get user by username
                user = SiteUser.objects.get(email=email_obj['email'])

                # Create and save user profile
                new_profile = UserProfile(user=user, activation_key=activation_key,
                                          key_expires=settings.EXPIRATION_DAYS)
                new_profile.save()
            except Exception as e:
                logger.exception(e)
                return render_to_response('500.html')

            # return HttpResponseRedirect('/register_success')
            return render_to_response('confirm.html', {'msg': msg})
    else:
        args['form'] = RegistrationForm()

    return render_to_response('userRegistration.html', args, context_instance=RequestContext(request))

Note: The code written in def register_user is core Djnago feature to handle user registration which I am exploiting. You can get these over internet

  1. If you need to render any form such as Order address, then create a form of angular and simple pass the value to Django using $http (the /url_called from $http will be mapped in urls.py).

  2. Make sure you are using {% verbatim %} and {% endverbatim %} whenever you are using {{ some_angular_variable }} because it contradicts withDjango Templatesyntax. Better to go forng-bind` as much as you can.

  3. Ignore $locationProvider for now if you are in initial stage. You’ll get some issues when using that with Django. I have a solution for that as well but for beginner, dont get into that. Try to integrate the plunkr code in your Django app and see if it’s working. Start small, dont jump to complicated examples.

Check one basic example of ngRoute.

In case you get stuck, post another question and put the link in the comment so that I can help you in that as well

Answered By – Shashank Vivek

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.