无法 Angular 加载路线
Can't Get Angular To Load Routes
我正在按照这个 tutorial 创建一个本地页面,它使用 django 和 angular 实现登录。但是我无法让按钮 register 显示任何内容。它只是将目录更改为/register。我认为这与路由有关。我没有错误。而且我不知道如何调试这个东西了,所以我 运行 别无选择。这是我的第一个 'website'.
进展不顺利的原因是我没有得到教程附带的入门项目。我想学习如何从头开始实现它。这意味着我的包更新了(bootstrap、django 等)。如果您需要更多信息,请告诉我。谢谢。
/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')
]
虽然这不是对这个问题的准确答案,但它是一个差异方法的答案
您提供的教程太长,没有包含在视频中。我曾在 Django
和 AngularJS
上创建电子商务网站。我建议你尽量不要混用 Django
和 AngularJS
以避免冲突。话虽这么说,我将简要介绍我为 User Registration
实现的内容:
我将用户表单与 AngularJS 表单分开,因为 Django 有自己的方式来处理用户管理(登录、注册、会话(使用 @login_required
)等) .
我在导航栏上提供了 <a href="/sign_up">Register</a>
。 (注意: /signup
是 url 映射到 urls.py
文件)
<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>
哪里url(r'^sign_up/', ('ecommerce.views.register_user')),
在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
如果您需要渲染任何 form
,例如 Order address
,那么创建一个 angular 的形式并将值简单地传递给 Django
使用 $http
(来自 $http
的 /url_called
将映射到 urls.py
)。
确保在使用 {{ some_angular_variable }} because it contradicts with
Django Templatesyntax. Better to go for
ng-bind` 时使用 {% verbatim %}
和 {% endverbatim %}
可以。
如果您处于初始阶段,请暂时忽略 $locationProvider
。将它与 Django
一起使用时会遇到一些问题。我也有一个解决方案,但对于初学者,不要进入那个。尝试将 plunkr code 集成到您的 Django 应用程序中,看看它是否正常工作。从小事做起,不要跳到复杂的例子。
万一你遇到困难,post另一个问题并把link放在评论中,这样我也可以帮助你
我正在按照这个 tutorial 创建一个本地页面,它使用 django 和 angular 实现登录。但是我无法让按钮 register 显示任何内容。它只是将目录更改为/register。我认为这与路由有关。我没有错误。而且我不知道如何调试这个东西了,所以我 运行 别无选择。这是我的第一个 'website'.
进展不顺利的原因是我没有得到教程附带的入门项目。我想学习如何从头开始实现它。这意味着我的包更新了(bootstrap、django 等)。如果您需要更多信息,请告诉我。谢谢。
/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')
]
虽然这不是对这个问题的准确答案,但它是一个差异方法的答案
您提供的教程太长,没有包含在视频中。我曾在 Django
和 AngularJS
上创建电子商务网站。我建议你尽量不要混用 Django
和 AngularJS
以避免冲突。话虽这么说,我将简要介绍我为 User Registration
实现的内容:
我将用户表单与 AngularJS 表单分开,因为 Django 有自己的方式来处理用户管理(登录、注册、会话(使用
@login_required
)等) .我在导航栏上提供了
<a href="/sign_up">Register</a>
。 (注意:/signup
是 url 映射到urls.py
文件)<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>
哪里url(r'^sign_up/', ('ecommerce.views.register_user')),
在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
如果您需要渲染任何
form
,例如Order address
,那么创建一个 angular 的形式并将值简单地传递给Django
使用$http
(来自$http
的/url_called
将映射到urls.py
)。确保在使用
{{ some_angular_variable }} because it contradicts with
Django Templatesyntax. Better to go for
ng-bind` 时使用{% verbatim %}
和{% endverbatim %}
可以。如果您处于初始阶段,请暂时忽略
$locationProvider
。将它与Django
一起使用时会遇到一些问题。我也有一个解决方案,但对于初学者,不要进入那个。尝试将 plunkr code 集成到您的 Django 应用程序中,看看它是否正常工作。从小事做起,不要跳到复杂的例子。
万一你遇到困难,post另一个问题并把link放在评论中,这样我也可以帮助你