如何将模板中的额外选项传递给Django中的视图?

时间:2015-11-19 10:17:01

标签: python ajax django django-templates django-urls

我正在使用django-voting应用程序让用户对对象进行投票,它运行正常。但现在事实证明,有多个模型需要投票,我决定从模板动态发送额外的选项到视图,使其更通用和可用。但它不起作用。

views.py

def vote_on_object(request, model, direction, post_vote_redirect=None,
        object_id=None, slug=None, slug_field=None, template_name=None,
        template_loader=loader, extra_context=None, context_processors=None,
        template_object_name='object', allow_xmlhttprequest=False):

目前网址和模板是这样的,它可以工作:

urls.py

link_dict = {
    'model': Link,
    'template_object_name': None,
    'allow_xmlhttprequest': True,
}
url(r'^links/(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$', vote_on_object, link_dict, name='vote_link'),

template.html

<form class="vote" method="POST" model="{{ object | model | lower }}" id="{{ object.pk }}" action="{% url 'vote_link' object_id=object.pk direction="up" %}">
  {% csrf_token %}
  <button type="submit"> + </button>
</form>

但是当我更改网址和模板时,请将模型动态发送到视图: urls.py

link_dict = {
    'template_object_name': None,
    'allow_xmlhttprequest': True,
}
url(r'^vote/(?P<model>[-\w\d\_]+)/(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$', vote_on_object, link_dict, name='vote_link'),

template.html

<form class="vote" method="POST" model="{{ object| model |lower}}" id="{{ object.pk }}" action="{% url 'vote_link' model=object|model object_id=object.pk direction="up" %}">
      {% csrf_token %}
      <button type="submit"> + </button>
</form>

我收到以下错误:"POST /vote/Link/1/upvote HTTP/1.1" 500 11350

另外我应该说模型过滤器是我为在模板中提取对象模型而定义的过滤器。

这是处理AJAX投票的vote.js:

$(document).ready(function() {
    //listen for click
    $('form.vote').on('submit', function(e){
        e.preventDefault();
        var vote_el = $(this);
        var
            url = vote_el.attr('action'),
            model = vote_el.attr('model'),
            direction = vote_el.attr('direction'),
            object_id = vote_el.attr('id'),
            allow_xmlhttprequest = "True" ;
            console.log(allow_xmlhttprequest, url, model, direction, object_id);
        $.ajax({
                type:'POST',
                url: vote_el.attr('action'),
                data: {
                    'model': model,
                    'object_id': object_id,
                    'direction': direction,
                },
                dataType: "json",
                success : function(data) {
                    console.log("Voted");
                    var pk = object_id;
                    $("p."+model+"-"+pk).text(data['score'].score);
                }
        });
    });

0 个答案:

没有答案