我有一个问题,我正在使用 Django 和 Restframework 来开发一个学校项目,但是当我使用 ajax 保存记录时,这会将我重定向到 api 页面而不是 CRUD 页面,只有管理员可以看到 api 页面( view)所以...你能帮我解决这个问题吗?
这是我的观点.py
class pacientesList(generics.ListCreateAPIView):
queryset = Paciente.objects.all()
serializer_class = pacienteSerializer
permission_classes = (IsAuthenticated, )
def list(self, request):
queryset = self.get_queryset()
serializer = pacienteSerializer(queryset, many=True)
return Response(serializer.data)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
这是我保存数据的 ajax 代码
$("#btnGuardarPaciente").click(function() {
$.ajax({
url: '{% url "core:pacientes_list" %}',
type: 'POST',
data: $("form").serialize(),
dataType: 'json',
success: function(data) {
console.log(data); // only to see if this is working
alert("Paciente agregado!.");
$("#exampleModal").modal('toggle');
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
});
});
它工作正常,这将记录保存到数据库中,但唯一的问题是,当我单击“保存”按钮时,这会将我重定向到我的 api 页面,而不是 CRUD 页面。
我的 html 表单
<form id="savePaciente" action="{% url 'core:pacientes_list' %}" method="post" >{%csrf_token%}
<md-form>
<input type="text" required name="first_name"
class="form-control" id="id_first_name" placeholder="Nombre(s)">
<input type="text" required name="last_name" class="form-control"
id="id_last_name" placeholder="Apellidos">
<label for="id_gender">Selecciona el sexo</label>
<select class="form-control" name="gender" id="id_gender" required>
<option value="F">Femenino</option>
<option value="M">Masculino</option>
<option value="O">Otro</option>
</select>
........
........
<input type="submit" class="btn btn-primary" value="Save"
id="btnGuardarPaciente">
</form>
和我的 urls.py
urlpatterns = [
url(r'^$', views.dashboard, name='dashboard'),
url(r'^historia-clinica/$', views.historiaClinicaView.as_view(), name='historia_clinica'),
#url(r'^paciente-create/$', views.createPaciente, name='paciente_create'),
#is this, the next url!
url(r'^pacientes/$', views.pacientesList.as_view(), name='pacientes_list'),
url(r'^paciente-detail/(?P<pk>[0-9]+)/$', views.pacienteDetail.as_view(), name='paciente_detail'),
]
我的 CRUD 位于/historia-clinica/
最佳答案
因为您将保存按钮放在带有定义的操作
的html表单中,所以当您按下它时,会发生两件事:
- 您的 ajax 代码已执行。
- 网络浏览器收集表单数据,并将其 POST 到表单的
action
中定义的 URL。这会导致重定向。
您可能不希望第二种情况发生。只需用 div
替换 form
block 即可。
关于jquery - 为什么 Django 在使用 ajax 保存记录后将我重定向到我的 api View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48082720/