如何在views.py中编写一个可以处理两个以上按钮的函数?

时间:2015-05-05 08:42:15

标签: python html django

例如,我的模板中有三个按钮,

   <button type="button" name = "remermber">I know that </button>
   <button type="button" name = "forget">Don't know </button>
   <button type="button" name = "not_appear">Too esay :)</button>

比我想在views.py中编写一个函数,可以判断不同的按钮用户点击并实现不同的功能。

我是一名非常新的代码学生。我不知道javascript和ajax,我能在Django中使用python实现这个功能吗?

form.py

    class OptionForm(forms.Form):   
       action = forms.CharField()

views.py

   def recite_words(request):
       if request.method == "GET":
            form = OptionForm(request.GET) 
           if form.is_valid():
                if form.cleaned_data["action"] == "remermber":
                     return HttpResponse("remermber") 
                elif form.cleaned_data["action"] == "forget":
                     return HttpResponse("forget")
                elif form.cleaned_data["action"] == "not_appear":
                      return HttpResponse("not_appear")   
           else:
                return HttpResponse("2")
       return HttpResponse("fail")

recite_words.html

   {% extends 'tag_study/base.html' %}
   {% load staticfiles %}
   {% block title %}Index{% endblock %}
   {% block body_block %}
   {% endblock %}

    {% block side_block %}
    {% if user.is_authenticated %}
        <form action="" method="GET"> 
        <button type="button" name="action" value="remermber">I know that </button>
        <button type="button" name="action" value="forget">Don't &nbsp know </button>
        <button type="button" name="action" value="not_appear">Too esay :)</button>
        </form> 
   {% endif %}


    {% endblock %}

3 个答案:

答案 0 :(得分:1)

假设这些按钮位于带有method="POST"的表单中,您可以简单地从POST字典中获取值并相应地发送:

if 'remember' in request.POST:
    return do_remember_function(request)
elif 'forget' in request.POST:
    return do_forget_function(request)
elif 'not_appear' in request.POST:
    return do_not_appear_function(request)

答案 1 :(得分:1)

首先,您需要(如果您想使用表单)每个按钮具有相同的名称:

DatabaseException

将此添加到您的表单:

<button type="button" name="action" value="remermber">I know that </button>
<button type="button" name="action" value="forget">Don't know </button>
<button type="button" name="action" value="not_appear">Too esay :)</button>

现在您可以在视图中使用它了:

action = forms.CharField()

如果您不想使用表单,可以通过if form.cleaned_data["action"] == "remember": pass # your code for remember action elif form.cleaned_data["action"] == "forget": pass # your code for forget action request.POST .get("action")访问您的按钮值:

答案 2 :(得分:1)

当然可以。只需使用按钮名称检查request.GET.get("action")参数:

request.POST