1

I am trying to create an analytics dashboard page for users that sign into my site. So if user 'DummyCo' signs in and goes to mywebsite.com/DummyCo/dashbord, they will see analytics relating to the model records where they are listed as the user (or client as I call them on the model.) I have the data working (shown below) but that simply allows me to display the count number.

What i'd like to do is start using this data in charts on chart.js which I have up and running, but it does not allow me to grab that signed-in user the way my other view does (chart view shown below also).

models.py

class Session(models.Model):
    uid = models.CharField(max_length=50, blank=True)
    cid = models.CharField(max_length=50, blank=True)
    client = models.CharField(max_length=50, blank=True)

views.py

class DashboardListView(LoginRequiredMixin, ListView):
    template_name = 'blog/dashboard.html'
    context_object_name = 'sessions'
    ordering = ['-session_date']

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Session.objects.filter(client=user).order_by('-session_date')

    def get_context_data(self, **kwargs):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        context = super().get_context_data(**kwargs)
        session_list = list(context['sessions']) 
        context['total_actions'] = Session.objects.filter(client=user).count()  # count function
        context['total_users'] = Session.objects.filter(client=user).values('uid').distinct().count()
        context['total_modules'] = Session.objects.filter(client=user).values('cid').distinct().count()
        context['sessions'] = session_list
        return context

@ login_required()
def dashboard(request):
    return render(request, 'blog/dashboard.html', {'title': 'Dashboard'})

urls.py

 path('<str:username>/dashboard/', views.dashboard and DashboardListView.as_view(), name='blog-dashboard')

html tags produced

{{ total_users }}, {{ total_actions }}, {{ total_modules }}

Now here is how i have chart.js set up:

views.py

class ChartData(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, format=None):
        session = Session.objects.filter(client='DummyCo').count()
        labels = ['Sessions', 'Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange']
        default_items = [session, 12, 15, 15, 22, 23, 20]
        data = {
            "labels": labels,
            "default": default_items,
        }
        return Response(data)

urls.py

    url(r'^api/chart/data/$', ChartData.as_view()),

html code with ajax and all the chart.js stuff

{% block jquery %}
var endpoint = '/api/chart/data/'
var defaultData = []
var labels = [];
$.ajax({
    method: "GET",
    url: endpoint,
    success: function(data){
        labels = data.labels
        defaultData = data.default
        setChart()
    },
    error: function(error_data){
        console.log("error")
        console.log(error_data)
        }
})

function setChart(){
    var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: '# of Votes',
                    data: defaultData,
                    backgroundColor:... (cutting off here for sanity)

But how can I replace that hard coded 'DummyCo' with the URL's username? This way, when one user logs out and new one logs in, they only see their own data.

I am thinking there is a simple way to replace (client='DummyCo') with something along the lines of (client=self.get('username') but i havent been able to crack it yet. Or maybe my URL doesn't know what page its actually displaying on on my site and I need to bring in a second view for the URL?

1 Answer 1

1

You need to provide the client in the URL:

url(r'^api/chart/data/<str:client>$', ChartData.as_view()),

and then you just have it in your get as a param:

def get(self, request, client):

I'm not sure why you have format=None there. It does not correspond to anything in your urls.py

Also, I would recommend not using Django REST framework's APIView for something that is not an API view (e.g. you're rendering a page, not providing a REST API endpoint). For that, just use plain Django class based views.

Sign up to request clarification or add additional context in comments.

1 Comment

So this is a weird case where the url path I am using is not actually the one I visit to see the chart. the chart itself is displaying on a url path('<str:username>/dashboard/', views.dashboard and DashboardListView.as_view(), name='blog-dashboard'), and "username" will be the exact same string as "client" in my use case. should I scrap the url(r'^api/chart/data/$', ChartData.as_view()), and try to make it work directly on the dashboard view? I just dont understand the ajax/java stuff going on, for example: the use of the $. The video I learned tried an API connection which I dont need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.