Skip to main content
 首页 » 编程设计

python之将请求(用户)传递给基于类的 View

2025年05月04日27freeliver54

作为对基于类的 View 有点陌生的人,我决定使用它们来驱动我正在处理的应用程序中的一些图表。

但是,我想让这个图表动态化,并希望它根据看到它的人而改变。

如何将请求(从中获取用户)传递给基于类的 View ?

下面是我的非工作实现(使用虚拟数据但没有传递请求):

查看:

class LineChartJSONView(BaseLineChartView, request): 
 
    user = request.user 
 
    def get_labels(self): 
        labels = [] 
        items = Item.objects.filter(user = user) 
        for i in items: 
            labels.add(i.name) 
        return labels 
 
    def get_data(self): 
        prices = [] 
        items = Item.objects.filter(user = user) 
        for i in items: 
            prices.add(i.price) 
        return prices 
 
line_chart = TemplateView.as_view(template_name='dashboard/test_chart.html') 
 
line_chart_json = LineChartJSONView.as_view() 

网址:

url(r'^chart_data/$', LineChartJSONView.as_view(), name='line_chart_json'),   
url(r'^chart/$', views.ViewBaseChart, name='basic_chart'), 

HTML:

{% load staticfiles %} 
<html> 
    <head> 
        <title>test chart</title> 
    </head> 
    <body> 
        <canvas id = "myChart" width="500" height="200"></canvas> 
        <!-- jQuery 2.2.3 --> 
        <script src="{% static 'plugins/jQuery/jquery-2.2.3.min.js' %}"></script> 
        <!-- Bootstrap 3.3.6 --> 
        <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> 
        <!-- ChartJS 1.0.1 --> 
        <script src="{% static 'plugins/chartjs/Chart.min.js' %}"></script> 
        <!-- FastClick --> 
        <script src="{% static 'plugins/fastclick/fastclick.js' %}"></script> 
        <!-- AdminLTE App --> 
        <script src="{% static 'dist/js/app.min.js' %}"></script> 
        <!-- AdminLTE for demo purposes --> 
        <script src="{% static 'dist/js/demo.js' %}"></script> 
        <!-- page script --> 
        <script type="text/javascript"> 
            $.get('{% url "line_chart_json" %}', function(data) 
            { 
                var ctx = 
                $("#myChart").get(0).getContext("2d"); 
                new Chart(ctx).Line(data); 
            }); 
        </script> 
    </body> 
</html> 

View (对于上面的静态 - 非基于类的 View ):

def ViewBaseChart(request): 
 
    context = {} 
    template = "dashboard/test_chart.html" 
 
    return render(request,template,context)  

我不确定我在这里是否正确使用了基于类的 View 概念,但是我发现这是迄今为止实现图表的唯一方法。

请您参考如下方法:

您不需要将 request 传递给基于类的 View ,如果您从 Django 的通用 View 中继承它们,它已经存在。基于通用类的 View 具有处理请求(GET、POST 等)的方法。

例如:

class LineChartJSONView(generic.View): 
    def get(self, request, *args, **kwargs): 
        """Handle GET request and return response""" 
 
    def post(self, request, *args, **kwargs): 
        """Handle POST request and return response""" 

阅读 Django 的基于通用类的 View 。它们充满了随时可用的功能。这是文档的链接 Django class based views introduction