Restrict new form creation on frontend in Django

Viewed 32

How can I restrict new form creation using Django formset? For eg. I want to present an "Add row" button to the user which will duplicate a set of input fields, AND, when the number of rows reaches 10, I want to give a prompt to the user that no more rows can be created.

For eg., in the image below, if the user clicks on "+" one more time, it should either do nothing or prompt the user that max number of rows reached or something like that.

enter image description here

Here is the code to clone more rows (I don't know yet how to restrict rows so no code for that):

function cloneMore(selector, prefix) {
    var newElement = $(selector).clone(true);
    var total = $('#id_' + prefix + '-TOTAL_FORMS').val();
    newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() {
        var name = $(this).attr('name').replace('-' + (total-1) + '-', '-' + total + '-');
        var id = 'id_' + name;
        $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
    });
    newElement.find('label').each(function() {
        var forValue = $(this).attr('for');
        if (forValue) {
          forValue = forValue.replace('-' + (total-1) + '-', '-' + total + '-');
          $(this).attr({'for': forValue});
        }
    });
    total++;
    $('#id_' + prefix + '-TOTAL_FORMS').val(total);
    $(selector).after(newElement);
    var conditionRow = $('.form-row:not(:last)');
    conditionRow.find('.btn.add-form-row')
    .removeClass('btn-success').addClass('btn-danger')
    .removeClass('add-form-row').addClass('remove-form-row')
    .html('<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>');
    return false;
} 
0 Answers
Related