Add a value during the create a new record.

Add a value during the create a new record. 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(
    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 @staticmethod def get_DT_RowAttr(rent): return {'data-pk':} @staticmethod def get_rent_period(rent): return 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));
                return cookieValue;

            var csrftoken = getCookie('csrftoken');

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

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

            let rt_period = {{}};

            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.val('rent_period_id', rt_period);

            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}

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


Thank you in advance for the help!


Sign In or Register to comment.