我正在这个tutorial之后创建一个本地页面,它使用django和angular实现登录。但我无法通过按钮注册来显示任何内容。它只是将目录更改为/ register。我认为这与路由有关。我没有错。而且我不知道如何调试这个东西,所以我已经没有选择了。这是我的第一个网站'。
原因并不顺利是因为我没有得到教程附带的入门项目。我想学习如何从头开始实现这一点。这意味着我的包是更新的(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')
]
答案 0 :(得分:0)
虽然它不是对这个问题的答案,但它是一个差异方法的答案
您提供的教程太长,不包含在视频中。我曾与Django
和AngularJS
合作创建了一个电子商务网站。我建议您尽可能多地混用Django
和AngularJS
以避免冲突。话虽如此,我将简要介绍我为User Registration
实施的内容:
我将用户表单与AngularJS表单分开,因为Django有自己的方式来处理用户管理(登录,注册,会话(使用@login_required
)等)。
我在导航栏上提供了<a href="/sign_up">Register</a>
。 (注意: /signup
是在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))
注意:用
def register_user
编写的代码是核心Djnago功能,用于处理我正在利用的用户注册。你可以通过互联网获取这些
如果您需要渲染任何form
,例如Order address
,则创建一个角度和简单形式,使用Django
将值传递给$http
(来自/url_called
的{{1}}将在$http
)中进行映射。
当您尽可能多地使用urls.py
Django模板{% verbatim %}
ng-bind`时,请务必使用{% endverbatim %}
和{{ some_angular_variable }} because it contradicts with
。
如果您处于初始阶段,请暂时忽略syntax. Better to go for
。使用$locationProvider
时,您会遇到一些问题。我也有一个解决方案,但初学者,不要进入那个。尝试将plunkr code集成到您的Django应用程序中,看看它是否有效。从小处着手,不要跳到复杂的例子。
如果您遇到问题,请发布其他问题并将评论中的链接放入评论中,以便我也可以帮助您