NickP
NickP

Reputation: 1414

Passing request (user) to a class based view

As someone who is a bit new to class based views, I have decided to use them to drive some charts in an application I am working on.

However, I would like to make this chart dynamic and would like it to change based on who is seeing it.

How can one pass a request (to get the user from) to a class based view?

Below is my non-working implementation (working with dummy data but no request being passed):

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:

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 (for static above - non classbasedview):

def ViewBaseChart(request):

    context = {}
    template = "dashboard/test_chart.html"

    return render(request,template,context) 

I am not sure I am using the class based view concept correctly here however, have found this to be the only way to implement charts thus far.

Upvotes: 3

Views: 5901

Answers (2)

Adilet Maratov
Adilet Maratov

Reputation: 1382

You do not need to pass request to class based views, it is already there for you if you inherit them from Django's generic views. Generic class based views have methods for handling requests (GET, POST, etc).

For example:

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

Read about Django's generic class based views. They are full of ready to use functionalities. Here is the link to the doc Django class based views introduction

Upvotes: 9

e4c5
e4c5

Reputation: 53734

Your class definition is incorrect. A CBV shouldn't inherit from HttpRequest (and I am not even sure if that's what you mean by request) . The correct definition is

class LineChartJSONView(BaseLineChartView):

This assumes of course that BaseLineChartView has been defined correctly. The following line should also be removed since it defines a global user and secondly because there isn't a request object there!

user = request.user

Now to get hold of a user instance, you need to override the get, post methods.

def get(self, request):
    user = request.user

Upvotes: 1

Related Questions