Django:向基于类的视图传递字符串参数无效

2024-09-27 23:26:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试过跟随this suggestion向基于类的视图传递字符串参数,但似乎不起作用。在

网址:

url(r'^chart/(?P<chart_name>\w+)/$',
        ChartView.as_view(chart_name='chart_name'), name="chart_url"),

观点:

^{pr2}$

应该重定向到视图的链接:

<a href="{% url 'chartboard:chart_url' chart_name='lords' %}">Sometext</a>

(名称空间'chartboard'在项目的urlconf中给出)。在

错误:

NoReverseMatch at /chart/lords/
Reverse for 'chart_url' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['chart/(?P<chart_name>\\w+)/$']

不管怎样,“test”被打印两次到控制台输出(为什么?)在

在Ubuntu 14.04.04上使用django 1.8.11和python3.4.3


Tags: 字符串nameview视图url参数aschart
1条回答
网友
1楼 · 发布于 2024-09-27 23:26:29

您应该使用kwargs访问chart_name

# urls.py
url(r'^chart/(?P<chart_name>\w+)/$',
    ChartView.as_view(), name="chart_url"),

# and then in the view

class ChartView(View):
    template_name = "chart.html"

    def get(self, request, *args, **kwargs):
        form = DatesForm()
        context = {
            'form': form,
            'chart_name': kwargs['chart_name'] # here you access the chart_name
        }
        return render(request, self.template_name, context)

为了实现这一点,您考虑过确保一个变量在模板中是可用的,并且通过在传递给模板呈现器的context中设置它来处理这个问题。在

这里您面临的问题是访问在url模式中定义的^{}。在

这里有更多关于django在您尝试访问URL时如何处理请求的documentation。在

相关问题 更多 >

    热门问题