当我尝试将数据从模板传递到视图时,Django QueryDict(request.GET)为空

时间:2016-03-31 23:40:49

标签: python django

在评论中回答。我删除了这一行:url(r'^$', RedirectView.as_view(url='/1')),并且所有内容都像我们想象的那样神奇地工作!

所以想法是用户点击一个按钮。该按钮将调用JavaScript函数。然后该功能将提交一份表格。该表单将调用views.py中的某个函数。

urls.py

urlpatterns = [
    url(r'^[0-9]*$', main, name='main'),
]

的index.html

<form action="{% url 'main' %}" method="GET" id="myForm">
    <input type="hidden" name="my_data" value="myValue">
</form>

<button href="javascript:{}" onclick="callMain();">main</button>

index_script.js

function callMain(){
    document.getElementById("myForm").submit();
}

views.py

def main(request):
    print(request.GET) #empty dict  <QueryDict: {}>

    #data = request.GET['my_data'] #<------ doesn't work.
    #data = request.GET.get('my_data', '') #doesn't throw error, but still empty.

    return render( ......."settings.html",  {'name': data})

单击按钮时,终端输出如下:

[31/Mar/2016 23:17:06] "GET /?my_Data=myValue HTTP/1.1" 302 0

request.GET为空的部分外,一切正常。我的错误在哪里?

编辑:

index.html呈现如下:

return render(request, "index.html", {'someContext': "value"})

以下是更多的runserver输出:

[01/Apr/2016 00:46:47] "GET /static/img/1.png HTTP/1.1" 304 0
[01/Apr/2016 00:46:48] "GET /?my_data=myValue HTTP/1.1" 302 0
<QueryDict: {}>

[01/Apr/2016 00:46:48] "GET /1 HTTP/1.1" 200 2246

我相信第1行正在获取图像。第2行是我点击按钮的时候。第3行是main()函数中的print语句。最后一行是main()末尾的渲染调用。

完成views.py

import re

from django.shortcuts import render
from MyImage.models import MyImage




def main(request):

    print(request.GET)

    image_file = get_image_file(request)

    if (MyImage.objects.filter(name=image_file).exists()):

        image = MyImage.objects.get(name=image_file)
        image.view_count = image.view_count + 1
        image.save()

        return render(request, "index.html", {'image': "img/"+image_file})
    else:
        return render(request, "index.html", {'image': "img/1.png"})


def get_image_file(request):
    i = request.get_full_path()
    i = re.sub("[^0-9]", "", i)
    image_file = i + ".png"
    return image_file

图片存储为1.png2.png3.png等。因此,如果用户访问www.mysite.com/2,则会看到2.png 。如果图片不存在,则显示默认图片。

完成urls.py

from django.conf.urls import include, url
from django.contrib import admin
from .views import main
from django.views.generic import RedirectView



urlpatterns = [
    url(r'^$', RedirectView.as_view(url='/1')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^[0-9]*$', main, name='main'),

]

1 个答案:

答案 0 :(得分:0)

我不确定为什么request.GET中有 nothing ,但是,服务器访问日志显示查询字符串包含名为my_Data的参数。 由于区分大小写my_Data != my_data

index.html中可能存在拼写错误,输入标记的name属性为my_Data而不是my_data