【问题标题】:How to create Django click buttons in ajax template for Python callback functions如何在 ajax 模板中为 Python 回调函数创建 Django 点击按钮
【发布时间】:2015-06-03 06:46:08
【问题描述】:

我正在尝试创建一个模板/ajax,其中三个按钮根据以下内容将三个不同的参数值发送回 Python 函数; - 一个变量 current_count 以值 0 开始,并为每个单击以下单击按钮之一的按钮更新 +-1;

Button1 - 单击按钮“前进”在单击视图函数 one_move() 时从模板返回字符“F”,其中它(字符“F”)作为参数传递给执行的 Python 函数当它接收到一个参数时。当单击按钮 Forward 返回到视图时,它还会将 current_count 的值增加 +1 当前值(通过 if 语句)

Button2 - 单击按钮“后退”在单击视图函数 one_move() 时从模板返回字符“D”,其中它(字符“D”)作为参数传递给执行的 Python 函数当它接收到一个参数时。当单击按钮 Backward 返回到视图时,它还会将 current_count 的值从当前值中减去 -1(通过 if 语句)

Button3 - 单击按钮“确定”在单击视图函数 one_move() 时从模板返回字符“S”,其中它(字符“S”)作为参数传递给 Python 函数,该函数在它收到一个 参数。当点击按钮OK时,current_count的值保持不变,即保持当前值。

上面的目的是实现一个pygame,其中通过views.py中one_move()中的Python回调函数传递的modelfields listview和sentence在html中显示为["Dave", 8, "to", "work"] 其中 8 是当前位置的标记,"went" 放在列表的左侧(由 Python 回调函数完成)。按下单击按钮“前进”会导致标记每次单击向右移动一步,从“去”到“到”,按下“后退”会导致标记每次单击向左移动一步,例如从“去”到“戴夫”,在列表的范围内。第三个按钮,OK,选择标记位置的单词,例如“went”。列表视图根据变量 current_count 中的当前位置编号进行更新。

在models.py中

class MoveInList(models.Model):
    click_char = models.CharField(max_length=70)
    current_count = models.IntegerField()
    listview = models.TextField()
    sentence = models.TextField()

    # function to update increase/decrease in (self)current_count value

    def count_changes(self):
        count = self.change_set.filter(is_public=True).count()
        self.current_count = count
        self.save()


    def __unicode__(self):
        return self.current_count


class OneMove(models.Model):
     click_char = models.CharField(max_length=70)
     current_count = models.IntegerField()
     listview = models.TextField()
     sentence = models.TextField()
     belongsTo = models.ForeignKey(MoveInList)
     def __unicode__(self):
        return self.click_count

在forms.py中

class MoveInListForm(forms.Form):
    click_char  = forms.CharField(max_length=70)
    current_count = forms.IntegerField()
    listview = forms.CharField(max_length=70)
    sentence = forms.CharField(max_length=70)

在views.py中

def MoveInListIndex(request):
    moves = MoveInList.objects.all()
    return render(request,"button.html", {"moves":moves})

def one_move(request,postID):
    one_moves = MoveInList.objects.get(id=postID)
    if request.method == 'POST':
        form = MoveInListForm(request.POST)
        if form.is_valid:
            post_one_move(request, one_move)

        else:
            MoveInListForm()

    # PYTHON CALLBACK function is used with params from template
    c = {"one_move":one_move,"form":form}
    c.update(csrf(request))

    return render(request,"button.html", c)

def post_one_move(request, one_move):


    click_count = request.POST['click_count']
    current_count = request.POST['current_count']
    listview = request.POST['listview ']
    sentence = request.POST['sentence']



    clickMove = OneMove(belongsTo=one_move,click_count=click_count,current_count=current_count,listview=listview,sentence=sentence)
    clickMove.save()

在 urls.py 中

url(r'^button$', MoveInListIndex),
url(r'^button/(?P<postID>\d+)$', one_move),

在带有 ajax.py 的 template.py 中

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form  method="post" action="">{% csrf_token %}

        Forward: <input type="submit" value="button""></input></br>
        Backward: <input type="submit" value="button""></input></br>
        OK: <input type="submit" value="button""></input></br>

         {{ form.as_p}}

    </form>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
    jQuery(document).ready(function() {
        $('#button').on('click', function (e) {
            var current_count = $('#button').val();
            var data = { current_count :current_count  };
            var args = { dataType: "json", type:"POST", url:"/button/",
                        data:data, complete:ajax_call_complete };
            $.ajax(args);
        });
    });
    var ajax_call_complete = function(res, status) {
        data = jQuery.parseJSON(res.responseText);
        // use data as a json response object here and
        // do something with the response data
    }
</script>
</body>
</html>

目前,模板 button.html 没有返回或显示任何内容,非常感谢有关如何让 ajax 运行的任何建议。

【问题讨论】:

  • 如果你调试到one_move,它真的被调用了吗?
  • 是的,python 回调已导入并在 one_move 中工作,在之前的尝试中,列表视图已显示在模板中,但是当我使用“F”代表前进、“D”代表后退等运行它时在键盘上,更改后的列表视图仅显示在 PyShell 中,尽管由 one_move 调用(请原谅,在上面的文本中拼写错误,应该是 one_move 而不是 one_view)
  • 总之,我需要一个 ajax 表单的帮助,该表单返回三个按钮的值,即来自 ajax 模板buttons.html 的字符“F”、“D”和“S”,以便它们可以作为参数传递给 one_move() 中的 Python 函数。此外,ajax 将更新/更改 current_count 变量值,以根据按下的按钮跟踪索引位置。

标签: python ajax django button callback


【解决方案1】:

我认为您可能需要使用HttpResponse() 而不是render() 将数据传回客户端:

from django.http.response import HttpResponse
import json

def one_move(request,postID):
    ...
    d = {"responseText": "your data here"}
    return HttpResponse(json.dumps(d))

那么您应该能够在您的ajax_call_complete() javascript 函数中获得返回

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 2013-02-26
    • 2017-11-24
    • 1970-01-01
    • 2017-04-21
    相关资源
    最近更新 更多