How to call model method in ajax through views_api and assign the value to table data in DRF?

Issue

This Content is from Stack Overflow. Question asked by SN Prasad

I am trying to understand the Django Rest Framework. As a beginner here, what I am trying is to call a method from a Model and update the value in the template. I am trying it from views_api.py with an ajax call. I was able to get other values, but I couldn’t get three values.

Here is what I have so far.

reviews/models.py

class Review(TimeStampedModel):
    project = models.ForeignKey('projects.Project', on_delete=models.CASCADE, related_name='reviews')
    fiscal_year = models.PositiveIntegerField(null=True, blank=True, db_index=True)
    fiscal_month = models.PositiveIntegerField(null=True, blank=True, db_index=True)
    has_validation = models.BooleanField('Has PFK', default=False)
    review_date = models.DateField(help_text='Date of the PFK', db_index=True)
    wp_validation_deadline = models.DateTimeField(blank=True, null=True, help_text='Deadline to validate WP')
    cutoff_date = models.DateTimeField(db_index=True,
                                       help_text='Up to when actuals are considered (date after accruals were entered)')
    fct_n_amount = models.DecimalField('FCT n amount', decimal_places=2, max_digits=12, null=True, blank=True)
    actuals_amount = models.DecimalField('Actual revenue traded', decimal_places=2, max_digits=12, null=True,
                                         blank=True, help_text='Cost to date (from monthly projectsales.xlsx)')

    events_amount = models.DecimalField('Total Events', decimal_places=2, max_digits=12, null=True, blank=True,
                                        help_text='In project currency (will be displayed in Thousands)')
    risks_real_amount = models.DecimalField('Total Risks - Most Likely', decimal_places=2, max_digits=12, null=True,
                                            blank=True,
                                            help_text='In project currency (will be displayed in Thousands)')
    risks_max_amount = models.DecimalField('Total Risks - Maximum', decimal_places=2, max_digits=12, null=True,
                                           blank=True,
                                           help_text='In project currency (will be displayed in Thousands)')
    opportunities_amount = models.DecimalField('Total Opportunities', decimal_places=2, max_digits=12, null=True,
                                               blank=True,
                                               help_text='In project currency (will be displayed in Thousands)')

    cje0_report = models.ForeignKey('sap.CJE0Report', verbose_name='CJE0 report', blank=True, null=True,
                                    on_delete=models.SET_NULL)
    # cji3_report = models.ForeignKey('sap.CJI3Report', blank=True, null=True, on_delete=models.SET_NULL)
    cji5_report = models.ForeignKey('sap.CJI5Report', verbose_name='CJI5 report', blank=True, null=True,
                                    on_delete=models.SET_NULL)
    fnl1_report = models.ForeignKey('sap.FNL1Report', verbose_name='FBL1N report', blank=True, null=True,
                                    on_delete=models.SET_NULL)
    hidden = models.BooleanField(default=False)
    is_frozen = models.BooleanField(default=False)
    revenue_frozen = models.BooleanField(default=False) #Bix-13280

    objects = VisibleManager()
    
    def get_cutoff_date_display(self):
        previous_month = self.review_date.replace(day=1) - datetime.timedelta(days=1)
        return previous_month

    def get_top_cje0(self):
        if not self.cje0_report:
            return None
        return 
        self.cje0_report.cje0element_set.filter(psp_element__code=self.project.code).first()

reviews/serializer.py

class ReviewSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Review
        fields = '__all__'

reviews/views_api.py

class SwaitchReviewViewSet(viewsets.ReadOnlyModelViewSet):          
    queryset = Review.objects.all()
    serializer_class = ReviewSerializer
    authentication_classes = []
    permission_classes = [AllowAny, ]

project_details.html

{% load static %}
{% load humanize %}
{% load strings %}
{% load django_bootstrap_breadcrumbs %}
{% load guardian_tags %}
{% load project_permissions %}
{% block header%}
{% endblock header%}
<div class="modal fade downloadPopupWrapper reviewsPopup" id="switchReview" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalCenterTitle">Reviewssssssssssssssssssssss</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <img src="{% static 'image/icon-close.svg' %}" alt="">
                        </button>
                    </div>
                    <div class="modal-body download_tableWrapper">
                    
                        <div class="tab-content" id="myTabContent">
                            <div class="tab-pane fade show active" id="reviews" role="tabpanel" aria-labelledby="reviews-tab">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                           
                                            <tr>
                                                <th scope="col">Fiscal Period</th>
                                                <th scope="col">Cut-off</th>
                                                <th scope="col">Review Date </th>
                                                <th scope="col">FCT (n-1) [CJE0]</th>
                                                <th scope="col">Actuals [CJE0]</th>
                                                <th scope="col"
                                                class="text-center"
                                                data-toggle="tooltip"
                                                data-placement="top"
                                                title="Review is frozen">Frozen
                                            </th>
                                            <th scope="col"
                                                class="text-center"
                                                data-toggle="tooltip"
                                                data-placement="top"
                                                title="PFK review">PFK
                                            </th>
                                            </tr>
                                        </thead>
                                        <tbody id = "tablebody">
                                          
                                           
                                        </tbody>
                                    </table>
                                </div>
                            </div>
     
                        </div>
                    </div>
                </div>
            </div>
        </div>

    {% block scripts %}
        <script>
            document.getElementById('switchReviewBtn').addEventListener('click', function (e) { 
                
            $.ajax({
                type: 'GET',
                url: "{% url 'reviews-list' %}",
                
                success: function (res) {
                    let table_data = ''
                    console.log(res);
                    res.forEach(element => {
                        console.log(element.id)
                        table_data += '<tr data-id="'+element.id+'" class="'
                        if(element.has_validation){
                            table_data += 'is-pfk'
                        }
                        if(element.is_frozen){
                            table_data += ' muted'
                        }
                        table_data += '"><td>' + element.fiscal_year + '-' + element.fiscal_month + '</td>'
                        table_data += '<td>' + element.get_cutoff_date_display + '</td>'
                        table_data += '<td>' + element.review_date + '</td>'
                        table_data += '<td>' + element.get_top_cje0.plan_v0 + '</td>'
                        table_data += '<td>' + element.get_top_cje0.actual + '</td>'
                        if(element.is_frozen){
                            table_data += '<td class="text-center">' + '<i class="fas fa-lock" data-toggle="tooltip" data-placement="top" title="Review is frozen">' + '</i>'
                            };
                        if(element.has_validation){
                            table_data += '<td class="text-center">' + '<img src="/static/admin/img/icon-yes.svg" alt="" data-toggle="tooltip" data-placement="top" title="PFK review">'
                            };
                        table_data +='</tr>'
                    });
                    // console.log(table_data)
                    $("#tablebody").html(table_data);
                 
                },
        
                errors: function (response) {
                    console.log(response.responseJSON.errors)
                }
            });
        }); 
            
    </script>
   
{% endblock scripts %}

I’m trying to call the methods element.get_cutoff_date_display, element.get_top_cje0.plan_v0, and element.get_top_cje0.actual in the above file, but I’m not getting any results. I couldn’t find the right way to do this. I’m sure I have things wrong. May I get any possible solution to this?



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?