将字典数据传递给Django视图

时间:2015-08-08 04:27:38

标签: django django-views django-urls

我对如何设置/调用我的网址以将数据字典从我的模板传递到我的视图感到困惑。我收到错误“NoReverseMatch at / categories / academy /”如何将data_dict(这是一本字典)传递给我的视图?

template.html

<a href="{% url 'polls:request_access' data_dict %}" class="btn btn-green btn-sm"><i class="fa fa-plus"></i> Join Group</a>

urls.py

# the category_slug in this case is "academy", see the error I mentioned above
url(r'^categories/(?P<category_slug>[-\w]+)/request_access/$', 'request_access', name='request_access')

views.py

def request_access(request, data):
    print("DJANGO VIEW- THIS IS NOT PRINTING")
    mydata = request.GET.get('data_dict')  # will this work?
    # do other stuff
    return render(request, 'polls/categories/group_access_requested.html',
        {'data': request})

3 个答案:

答案 0 :(得分:1)

尝试创建装饰器以执行data_dict的编码。

import urllib
from django import template
register = template.Library()

@register.filter
def get_encoded_dict(data_dict):
    return urllib.urlencode(data_dict)

然后在模板中,您可以将其用作:

<a href="{% url 'polls:request_access' my_category_slug %}?{{data_dict|get_encoded_dict}}" class="btn btn-green btn-sm"><i class="fa fa-plus"></i> Join Group</a>

这应该解决你的问题。

答案 1 :(得分:0)

我建议使用Ajax。以下是一个基于以下代码的示例:

<强> HTML:

# Instead of passing info through here, I would set something up in your model to handle that
<a href="{{ object.get_some_url }} class="ajax_call" data="enter_value_here">Join Group</a>

<强> models.py:

class Model(models.Model):
    field = models.ForeignKey(OtherModel)

    def get_some_url(self):
        return reverse('url_name',
                       kwargs={'url_argument': self.field.value})

<强> AJAX:

$('.ajax_call').click(function(e){
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "{% url 'some_url' %}",
        data: {
            "data_to_be_sent": $(this).attr("data"),
            csrfmiddlewaretoken: "{{ csrf_token }}",
        },
        dataType: "json",
        success: function(data) {
            if (data.worked) {
                // Do something here
            } else {
                // Do something else here
            }
        },
        error: function (rs, e) {
            alert('Sorry, there was an error.');
        }
    });
});

<强> views.py:

from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_http_methods

from datetime import datetime


@require_http_methods(['POST'])
def textbook(request):
    data_received = request.POST.get('data_to_be_sent')
    # Do something with this data
    if something_was_done:
        # Do something?
        worked = True
    else:
        # Do something else?
        worked = False

    data = {
        'worked': worked
    }
    return JsonResponse(data)

答案 2 :(得分:0)

要将参数传递给模板中的网址,您必须对参数进行编码,然后将其附加到网址的末尾。

您需要执行以下操作:

<a href="{% url 'polls:request_access' my_category_slug %}?key1=value1&key2=value2.." class="btn btn-green btn-sm"><i class="fa fa-plus"></i> Join Group</a>

另一种选择是使用urllib.urlencode()库中的urllib将字典编码为url编码的参数。只需将字典传递给它,它就会将其转换为url编码的字符串。

In [1]: import urllib

In [2]: data_dict = {'key1':'value1', 'key2':'value2', 'key3':'value3'}

In [3]: urllib.urlencode(data_dict)
Out[3]: 'key3=value3&key2=value2&key1=value1'

然后,您可以将此url编码的字符串作为my_url_encoded_string传递给上下文,并将其放在网址的末尾。

在您的观看中,您可以通过其键访问data_dict

value1 = request.GET.get('key1') # value of 'key1'
value2 = request.GET.get('key2') # value of 'key2'