我正在尝试在我的Django网站上进行POST隧道。我基本上要做的是“启用”PUT和DELETE。所以,现在我正在努力与DELETE。在我的template.html中,我有以下内容:
<form action="/photos/{{ photo.id }}/" method="POST" >
{% csrf_token %}
<button type="submit" class="btn btn-link" >Delete photo</button>
<input id="override" type="hidden" name="_method" value="DELETE"/>
</form>
通过这种方式,我试图通过为我的request.POST提供额外的属性“_method”来删除照片。
我写了一个中间件类,应该在我的请求中用“DELETE”替换“POST”:
class HTMLTunneling(object):
def process_request(self, request):
if request.POST.has_key('_method'):
http_method = request.POST['_method']
if http_method.lower() == 'put':
request.method = 'PUT'
request.META['REQUEST_METHOD'] = 'PUT'
request.PUT = QueryDict(request.body)
if http_method.lower() == 'delete':
request.method = 'DELETE'
request.META['REQUEST_METHOD'] = 'DELETE'
request.DELETE = QueryDict(request.body)
return None
但是,django一直在投掷
Forbidden (403)
CSRF verification failed. Request aborted
每次点击我的删除按钮。如果我删除中间件,它的工作原理。如果我做任何会禁用删除功能的东西,它会起作用。我不明白。任何人都可以帮助我吗?
以下是应该处理此请求的视图:
@login_required
def handle_image(request, image_id):
"""
Main handler for an image. Checks what kind of a request came and redirects
traffic according to it.
"""
if request.method == 'GET':
return show_image(request, image_id)
elif request.method == 'DELETE':
return delete_image(request, image_id)
elif request.method == 'PUT':
# print("Inside put")
# update image with a like or comment
if request.PUT.has_key('publ'):
return privacy(request, image_id)
if request.PUT.has_key('like'):
return like_image(request, image_id)
if request.PUT.has_key('comm'):
return comment(request, image_id)
它实际上只是调用相应的视图。例如,隐私视图如下所示:
@login_required
def privacy(request, image_id):
try:
# user = CustomUser.objects.get(pk=user_id)
photo = Photo.objects.get(pk=image_id)
except:
raise Http404
accessor = request.user.customuser
if accessor != photo.owner:
return HttpResponseForbidden("Forbidden")
if request.PUT['publ'] == "true":
photo.public = True
photo.save()
elif request.PUT['publ'] == "false":
photo.public = False
photo.save()
c = image_context(photo, accessor)
return render(request, 'photos/view_image.html', c)
它只是将图像属性设置为public或private。 我是按照here和here的建议完成的。我当然没有任何AJAX东西,只有普通的HTML。