django - collecting data from a HTML <select>

不打扰是莪最后的温柔 提交于 2019-11-30 05:38:50

问题


I've seen a couple of documents on how to collect the data from a HTML statement in Django but none of them were very clear to me. Does anybody have a real working example to share?

In my case I have something like this in my template file:

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

What goes in the views.py in order to collect the selected value? Thank you!


回答1:


If it's a GET request, request.GET['my_options']. If it's a POST, then request.POST['my_options']. This will be a string, either "1" or "2" (or "<script>alert('I hacked you!')</script>")

Either way, it's probably better to use the Django forms framework to save you the hassle of writing the HTML, and sanitizing the returned values.




回答2:


Manage data via 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

One thing that may be useful with forms in Django is to make different things if you make a POST to the URL or just load it:

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(...)

There are 2 render_to_response in case you need to do different things if the view was just loaded or receive a POST.

Manage data via 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


来源:https://stackoverflow.com/questions/4786564/django-collecting-data-from-a-html-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!