1 votes

In what method to implement the logic

Hello I am making a web application in Django. Is to store the final grades of the subjects of the students, I am using CBV.

class StudentScore(DetailView):
    model = Student
    template_name = 'student_info.html'
    notes = ScoreModel.objects.all()
    scores = []

    for score in ScoreModel.objects.all():
        for student in model.objects.all():
            if score.student.pk == student.first_name:
                scores.append(score.score)

    finalnote = float(sum(scores)/20)


    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['finalnote'] = self.finalnote
        context['scores'] = ScoreModel.objects.all()
        return context

Then I averaged all the notes, so I would like to access the object that I generated by the class DetailView.

I was also thinking of 'filter' for the path, as in the path receipt both the primary key like first_name in the form of slug.

I would like to know how to do this by using a CBV because I don't want to use FBV.

Thank you!!

2voto

Julio Cesar Points 81

Small portion of the documentation about the view, DetailView:

While this view is executing, self.object contain the object on which it is operating the vista.

Then to be able to access the object that generates the view DetailView, better said, the object on which it operates the vista - DetailView, you'll have to do it through a self.object, you can access to self.object from any method except for the method get_objetc.

It would also be better in my opinion to make the management and the calculation of the scores in the same method get_context_data, in the following way:

class StudentScore(DetailView):
    model = Student
    template_name = 'student_info.html'
    notes = ScoreModel.objects.all()

    def get_context_data(self, **kwargs):
        scores = []
        for score in ScoreModel.objects.all():
            for student in model.objects.all():
                if score.student.pk == student.first_name:
                    scores.append(score.score)

        ctx = super().get_context_data()
        ctx['finalnote'] = float(sum(scores)/20)
        ctx['scores'] = ScoreModel.objects.all()

        return ctx

Well I hope I have helped. By the way what do you mean with path or filter by path? To be able to help you.

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X