首页 > 解决方案 > 无法从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);  
                  }  
                });  

标签: pythondjango

解决方案


  • 创建一个视图来呈现模板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
    }
});

推荐阅读