python - 无法从views.py 重定向
问题描述
我想通过views.py 将我的url 重定向到一个HTML 页面(Chatbot.html)。
下面是我正在使用的代码。
我可以看到它进入 if 语句并给我错误
errorSyntaxError: Unexpected token < in JSON at position 0
下面是我的views.py代码
from django.shortcuts import render,get_object_or_404,render_to_response
from django.http import HttpResponse
import json
from django.views.generic import TemplateView
from django.views import View
from .forms import HomeForm
from django.http import JsonResponse
from .models import Employee
class Login(View):
def post(self,request,*args,**kwargs):
response_data={}
response_data['email']= request.POST['email']
response_data['password']= request.POST['password']
data = Employee.objects.all()
for emp in data:
emailid = emp.usr_email
passkey = emp.usr_password
if emailid == request.POST['email'] and emp.usr_password == request.POST['password']:
return render(request,'bot/chatbot.html')
else:
return HttpResponse(json.dumps(response_data), content_type="application/json")
这是我的ajax代码
$.ajax({
type: "POST",
url: "/bot/login/",
dataType: "json",
async: true,
data:{
csrfmiddlewaretoken: '{{ csrf_token }}',
email: email,
password: password
},
success: function(json){
},
error : function(request, status, error) {
var val = request.responseText;
alert("error"+error);
}
});
解决方案
- 创建一个视图来呈现模板
bot/chatbox.html
。 - 使用给定的电子邮件和密码优化搜索员工。
- 如果凭据正确,则返回指向您创建的视图的 url,否则返回错误。
示例:
def chatbox_index(request):
context = {}
template_name = "bot/chatbox.html"
return render(request, template_name, context=context)
# add `url(r'chatbox/$', views.chatbox_index, name='chatbox') in app's `urls.py`
from django.urls import reverse
class Login(View):
def post(self,request,*args,**kwargs):
response_data={}
response_data['email']= request.POST['email']
response_data['password']= request.POST['password']
# optimize searching for employee using Django ORM
employee = Employee.objects.filter(
usr_email=request.POST['email'],
usr_password=request.POST['password']
).first()
if employee is not None:
response = {"success_url": reverse('chatbox')}
return HttpResponse(
json.dumps(response),
content_type="application/json",
status=201
)
else:
response = {"errors": "Invalid Credentials"}
return HttpResponse(
json.dumps(response),
content_type="application/json",
status=401
)
# ajax callbacks
$.ajax({
...,
success: function(data) {
if (data.success_url) {
window.location.href = data.success_url;
}
},
error: function(error) {
var errors = error.errors;
// display user the errors
}
});
推荐阅读
- angular - 如何在 navigationEnd 事件中获取当前路线配置?
- python - 在 Python 中计算两个图像之间绝对差异之和的最快方法是什么?
- swift - 录制因多任务处理和内容大小调整而中断
- android - Android从通知中多次打开活动
- python - 在 Python for 循环中使用 Pandas shift()
- javascript - Handsontable:将纪元时间戳编辑为日期
- hyperledger-fabric - 我在使用 npm 运行 fabcar 示例时出错
- apache-spark - Spark 作业在 7 小时后因 Yarn 上的 FileNotFoundException 而失败
- html - 随着小型设备上的内容不断增长的部分
- javascript - 提交按钮后显示消息