django - 从 HTML <select> 中收集数据

6 投票
2 回答
17486 浏览
提问于 2025-04-16 10:32

我看到过一些关于如何在Django中从HTML语句收集数据的文档,但对我来说都不是很清楚。有没有人能分享一个真正有效的例子?

在我的模板文件中,我有这样的内容:

<select title="my_options">
   <option value="1">Select value 1</option>
   <option value="2">Select value 2</option>
</select>

那么在views.py中应该写些什么来收集选中的值呢?谢谢!

2 个回答

0

通过POST管理数据

def yourView(request):
    # Use '.get('id', None)' in case you don't receive it, avoid getting error
    selected_option = request.POST.get('my_options', None)  

    if selected_option:
        # Do what you need with the variable

在Django中,处理表单时,有一个很有用的点就是:当你向某个网址发送POST请求时,可以做一些特别的事情,而如果只是加载这个网址,则可以做另外的事情。

def yourView(request):

    if request.POST:  # If this is true, the view received POST
        selected_option = request.POST.get('my_options', None)
        if selected_option:
            # Do what you need to do with the variables
        return render_to_response(...)

return render_to_response(...)

这里有两个 render_to_response,这样你就可以根据视图是被加载还是接收到POST请求来执行不同的操作。

通过GET管理数据

def yourView(request):
    # Use '.get('id', None)' in case you don't receive it, avoid getting error
    selected_option = request.GET.get('my_options', None)  

    if selected_option:
        # Do what you need with the variable
6

如果是GET请求,你可以用 request.GET['my_options'] 来获取数据。如果是POST请求,那就用 request.POST['my_options']。这个获取到的值是一个字符串,可能是 "1""2"(也可能是 "<script>alert('I hacked you!')</script>" 这样的内容)

无论是哪种情况,使用 Django表单框架 会更好,这样可以省去你自己写HTML的麻烦,还能确保返回的值是安全的。

撰写回答