如何从一个角度返回到Django?

2024-04-20 03:17:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在django1.8应用程序中,我有一个使用角度.js. 在Angular将表单提交给Django Rest框架之后,我想转到另一个Django视图。我的问题是除了使用$windows.location.href?

目前我正在使用$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框架,如下所示:

        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];
            }

(...)

有什么不同的方法吗?你知道吗


Tags: djangonamerestidurl表单dataresponse
1条回答
网友
1楼 · 发布于 2024-04-20 03:17:40

如果希望django控制重定向,不要使用AJAX发布表单,只需使用常规表单将其发布回django,这样就可以将用户重定向到另一个视图。你知道吗

例如

<form name="newPatientForm" method="POST" action=""> 
{% csrf_token %}
(...)
</form>

在你看来:

def new_patient_form_submit(request):
    name = request.POST['. . .']
    . . .
    return redirect('another_view_name')

或者,您可以让REST端点返回一个带有要重定向到的URL的成功JSON响应,这样您就不必将其硬编码到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

相关问题 更多 >