将字典数据传递到Django视图 [英] Pass dictionary data to Django view

查看:97
本文介绍了将字典数据传递到Django视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm confused on how to set up/call my url to pass a dictionary of data from my template to my view. I'm getting an error "NoReverseMatch at /categories/academy/" How can I pass data_dict, which is a dictionary, to my view?

template.html

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})


推荐答案

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

Try creating a decorator to perform the encoding of the data_dict.

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

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

然后在您的内部模板,您可以将其用作:

Then inside your template, you can use it as:

<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>

这应该可以解决您的问题。

This ought to solve your problem.

这篇关于将字典数据传递到Django视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆