在 Django 1.8 应用程序中,我有一个使用 Angular.js 发布的表单。在 Angular 将表单提交到 Django Rest Framework 后,我想移动到另一个 Django View 。我的问题是除了使用 $windows.location.href 之外如何移动到另一个 Django View ?
目前我正在使用 $windows.location.href 但我希望 Django(不是 Javascript/Angular)移动到另一个页面。这是我现在的做法 - 为了简洁起见,这是我的模板中此表单的一小部分:
<div ng-app="pacjent">
(...)
<div ng-controller="NewPatientCtrl">
(...)
<form name="newPatientForm" ng-submit="newPatientForm.$valid && submitNewPatientForm()" ng-init="initialize('{{user.id}}')" novalidate>
{% csrf_token %}
(...)
</form>
此表单将所有数据发布到 Django Rest Framework,如下所示:
function submitNewPatientForm(){
/* it's prime goal is to submit name,surname, age & phone to createNewPatient API */
$scope.setBusy = true;
savePatient = $http({
method: 'POST',
url: 'http://localhost:8000/pacjent/api/createNewPatient/',
data: $scope.newPatient,
})
.then(function successCallback(response){
newPatient = response.data['id'];
createNewTherapyGroup();
url = patientDetailView + response.data.id + '/';
$window.location.href=url; # I DON"T WANT TO USE THIS, but I don't know how!
}, function errorCallback(response){
if (response['data']['name'] && response['data']['surname']) {
$scope.newPatientForm.newPatientName.$setValidity("patientExists", false);
$scope.errors.newPatientName =response.data['name'][0];
}
(...)
有什么不同的方法吗?
最佳答案
如果您希望 django 控制重定向,请不要使用 AJAX 发布表单,只需使用常规表单将其发布回 django,以便您可以将用户重定向到另一个 View 。
例如,
<form name="newPatientForm" method="POST" action="">
{% csrf_token %}
(...)
</form>
在您看来:
def new_patient_form_submit(request):
name = request.POST['. . .']
. . .
return redirect('another_view_name')
或者,您可以让 REST 端点返回成功的 JSON 响应以及要重定向到的 URL,这样您就不必将其硬编码到 JS 文件中:
.then(function successCallback(response){
newPatient = response.data['id'];
var next = response.data['next']; // get the next URL to go to from the django REST endpoint
createNewTherapyGroup();
$window.location.href = next; // redirect to the django-provided route
关于javascript - 如何从 Angular 表单返回 Django?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41140079/