Django:将字符串参数传递给基于类的视图不起作用

时间:2016-04-07 14:33:07

标签: python django django-views django-class-based-views

我已尝试按照this suggestion将字符串参数传递给基于类的视图,但它似乎不起作用。

网址:

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

观点:

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

    def post(self, request, *args, **kwargs):
        form = DatesForm(request.POST)
        context = {
            'form': form
        }
        return render(request, self.template_name, context)

    def get(self, request, *args, **kwargs):
        print("test")
        form = DatesForm()
        # fetch plot data (default values used)
        context = {
            'form': form,
            'chart_name': self.chart_name
        }
        return render(request, self.template_name, context)

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

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

(名称空间&#39; chartboard&#39;在项目的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+)/$']

它的价值,&#34;测试&#34;被打印两次到控制台输出(为什么?)

在Ubuntu 14.04.04上使用django 1.8.11和python 3.4.3

1 个答案:

答案 0 :(得分:0)

您应该使用$ GIT= brew update

访问chart_name
kwargs

您考虑实施此项目的帖子是为了确保变量在模板中可用,并通过在# 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) 中设置并传递给模板渲染来处理。

您在此遇到的问题是访问网址格式中定义的named group

以下是关于当您尝试访问网址时django如何处理请求的documentation