Add a value during the create a new record.

Add a value during the create a new record.

bruce@harrisonemail.combruce@harrisonemail.com Posts: 8Questions: 3Answers: 0

I am running Editor with a Django backend and using djangorestframework-datatables-editor, a REST framework to manage the API. the Django app works well.

My goal is when I click on the editor New button, I need to add, value to one of my fields, rent_period, before the record is saved. I was trying to use preCreate(), but I am open to alternative approaches. The value rent_period is passed to the webpage using Django's Template language. The rent_period value is constant for the webpage.

In Django, I have the following model:

class Rents(models.Model):
    rent_period = models.ForeignKey(
        RentPeriod,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        related_name='rent'
    )
    start_date = models.DateField()
    end_date = models.DateField()
    amount = models.DecimalField(max_digits=25, decimal_places=2, default=0)

    class Meta:
        verbose_name = 'Rent'
        verbose_name_plural = 'Rents'
        ordering = ['start_date']

    def __str__(self):
        title = f"{self.start_date} - {self.end_date}"
        return title

My serializer looks like:


class RentSerializer(serializers.ModelSerializer): DT_RowId = serializers.SerializerMethodField() DT_RowAttr = serializers.SerializerMethodField() @staticmethod def get_DT_RowId(rent): return rent.pk @staticmethod def get_DT_RowAttr(rent): return {'data-pk': rent.pk} @staticmethod def get_rent_period(rent): return rent.rent_period.id class Meta: model = Rents fields = ( 'DT_RowId', 'DT_RowAttr', 'rent_period', 'start_date', 'end_date', 'amount' )

and my JS looks like:

        $(document).ready(function () {

            function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }

            var csrftoken = getCookie('csrftoken');

            function csrfSafeMethod(method) {
                // these HTTP methods do not require CSRF protection
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }

            $.ajaxSetup({
                beforeSend: function (xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

            let rt_period = {{ rent_period.id}};

            let editor = new $.fn.dataTable.Editor({
                ajax: "/api/rents/editor/?format=datatables",
                table: "#rent",
                fields: [
                    {
                        label: "Start Date",
                        name: "start_date",
                    }, {
                        label: "End Date:",
                        name: "end_date"

                    }, {
                        label: "Amount:",
                        name: "amount",
                    },
                ]
            });

            editor.on('preCreate', function () {
                    editor.create(false);
                    editor.val('rent_period_id', rt_period);
                    editor.submit();
                }
            );


            let table = $('#rent').DataTable({
                "serverSide": true,
                dom: "Bfrtip",
                "ajax": "/api/rents/?format=datatables",
                "columns": [
                    {"data": "start_date"},
                    {"data": "end_date"},
                    {"data": "amount"},
                ],
                select: true,
                buttons: [
                    {extend: "create", editor: editor},
                    {extend: "edit", editor: editor},
                    {extend: "remove", editor: editor}
                ]
            });

            table.buttons().container()
                .appendTo($('.col-md-6:eq(0)', table.table().container()));

        });
    </script>

Thank you in advance for the help!

Answers

This discussion has been closed.