在views.py django rest框架中发布后重定向

时间:2017-06-27 09:48:34

标签: python django rest

我正试图弄清楚如何在Django休息框架应用程序中发布后重定向到一个简单的html响应页面。

这就是网络中模型的样子:

文件上传表格:

form for file upload

点击发布按钮后,我在 views.py 中有代码,应该将其重定向到简单的html上,但是它会保留在同一页面上,但查询结果为空,我不知道我是什么我做错了吗?

from rest_framework import viewsets
from api.models import UploadImage
from api.serializers import UploadedImageSerializer
from rest_framework import  permissions
from rest_framework.parsers import MultiPartParser,FormParser
from sqlite_queries import user_ips

class FileUploadViewSet(viewsets.ModelViewSet):
    #create queryset view
    permission_classes = (permissions.IsAuthenticated,)
    queryset = UploadImage.objects.all()
    serializer_class = UploadedImageSerializer
    parser_classes = (MultiPartParser, FormParser,)

    #after post action get this
    def perform_create(self, serializer):
        #grab request
        image_name = self.request.data['image']
        meta_data = self.request.META
        username = self.request.user
        REMOTE_ADDR = meta_data['REMOTE_ADDR']

        #check user status, how many ip's he had over last 24 hours
        user_status = user_ips(username)

        #if user has more than allowed redirect to html page
        if user_status == 400:
            print ("how to redirect here?")
            #return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
            #return HttpResponseRedirect("limit.html")

        #if user iz valid continue with upload
        serializer.save(user = username, meta_data= meta_data,remote_ip=REMOTE_ADDR)

2 个答案:

答案 0 :(得分:0)

Dragon,假设你使用ajax进行了这个api调用,你可以将响应返回给调用ajax函数,你可以使用window.location读取状态/响应和重定向。

Django休息框架

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Javscript Side

$.ajax({
url: 'link to your django restframe work api',
success: function (response) {
    $('#post').html(response.responseText);
},
error: function (jqXHR, exception) {
    var msg = '';
    if (jqXHR.status === 0) {
        msg = 'Not connect.\n Verify Network.';
    } else if (jqXHR.status == 400) {
        window.location = "limit.html" //window.location = "{% django named url to limit view %}";
    } else if (jqXHR.status == 500) {
        msg = 'Internal Server Error [500].';
    } else {
        msg = 'Uncaught Error.\n' + jqXHR.responseText;
    }        
},

});

您可以在错误部分捕获400。或者,您也可以发送带有自定义消息的200,并在ajax成功函数中处理相同的内容。

希望有所帮助

答案 1 :(得分:0)

如果我理解正确,您不希望某些用户在24小时内过度使用来自不同IP地址的特定登录次数。您可以尝试这样,但我建议您在虚拟环境python中执行这些步骤。

1.您可以从views.py中删除这部分代码:

#check user status, how many ip's he had over last 24 hours
user_status = user_ips(username)

#if user has more than allowed redirect to html page
if user_status == 400:
    print ("how to redirect here?")
    #return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    #return HttpResponseRedirect("limit.html")

2.将此sqlite_queries.py复制到Python 3 \ Lib,以便它可以全局使用,如果你没有。

3.然后我们要停止从超过允许登录数量的用户名登录来自不同的IP地址。基于与Fazil Zaid的对话,你只想用Django Rest Framework来实现它,这就是你可以做到的。我们该怎么做?

3.1您必须打开Python 3 \ Lib \ site-packages \ django \ contrib \ auth \ forms.py

3.2在里面你将进入函数confirm_login_allowed,这是在AuthenticationForm类内部,并在函数的开头和这行

from sqlite_queries import user_ips
#check user status, how many ip's he had over last 24 hours
user_status = user_ips(user,r'full_path_to_you_sqlite_db')

#if user has more than allowed redirect to html page
if user_status == 400:
    raise forms.ValidationError(
        self.error_messages['inactive'],
        code='inactive',
    )

现在,如果用户与您的sql查询匹配,他将在登录时停止并显示消息"此帐户处于非活动状态。"。

3.4如果要将错误消息更改为某些自定义文本,您应该转到AuthenticationForm类的顶部,在那里您将找到字典error_messages。只需将您的密钥和值添加到字典即可。

enter image description here