How can I add permissions in django model forms?

It is a dynamic model form, Is there any way to add permissions in django forms.py ?

It is coming by using crispy forms.

My model_form.html:-

<div>
{% if form.pre_form_info %}
<div class='alert alert-info alert-block' role='alert'>
{{ form.pre_form_info }}
</div>
{% endif %}
{% if form.pre_form_warning %}
<div class='alert alert-warning alert-block' role='alert'>
{{ form.pre_form_warning }}
</div>
{% endif %}
{% block non_field_error %}
{% if form.non_field_errors %}
<div class='alert alert-danger alert-block' role='alert'>
  <b>Error Submitting Form:</b>
  {{ form.non_field_errors }}
</div>
{% endif %}
{% endblock %}
</div>

{% block pre_form_content %}
{% endblock %}

{% block form %}
<form method="post" action='' class='js-modal-form' enctype="multipart/form-data">
  {% csrf_token %}
{% load crispy_forms_tags %}
  
  {% block form_data %}
  {% endblock %}
  
  {% crispy form %}

</form>

{% endblock %}

{% block post_form_content %}
{% endblock %}


<script>
 var app ={
      init:function(){

        app.onChangeUserTpe();
        $( document ).ready(function() {
          var txt = $('#select2-id_is_superuser-container').text();
          app.showAndHide(txt);
        });
      },
      onChangeUserTpe:function(){
        $('.controls').change(function(){
          var txt = $(this).find('#select2-id_is_superuser-container').text();
          app.showAndHide(txt);
        });
      },
      showAndHide:function(txt){
        if(txt == 'Admin') {
         $('#div_id_job_role').hide();
        } else {
          $('#div_id_job_role').show();
        }
      },

  };
  app.init();
$('#id_username').on('keyup',function(e){
 		$('#error_1_id_username').remove()
});
$('#id_email').on('keyup',function(e){
 		$('#error_1_id_email').remove()
});
$('#id_job_role').on('change',function(e){
 		$('#error_1_id_job_role').remove()
});
$('#id_name').on('keyup',function(e){
 		$('#error_1_id_name').remove()
});
$('#id_description').on('keyup',function(e){
 		$('#error_1_id_description').remove()
});
$('#id_reference').on('keyup',function(e){
 		$('#error_1_id_reference').remove()
});
$('#id_title').on('keyup',function(e){
 		$('#error_1_id_title').remove()
});
$('#id_part').on('change',function(e){
 		$('#error_1_id_part').remove()
});
$('#id_supplier').on('change',function(e){
 		$('#error_1_id_supplier').remove()
});
</script>

My forms.py:-

class CreateStockItemForm(HelperForm):
    """ Form for creating a new StockItem """

    serial_numbers = forms.CharField(label='Serial numbers', required=False, help_text=_('Enter unique serial numbers (or leave blank)'))

    class Meta:
        model = StockItem
        fields = [
            'part',
            'supplier_part',
            'location',
            'quantity',
            'batch',
            'serial_numbers',
            'delete_on_deplete',
            'status',
            'notes',
            'URL',
        ]

    # Custom clean to prevent complex StockItem.clean() logic from running (yet)
    def full_clean(self):
        self._errors = ErrorDict()
        
        if not self.is_bound:  # Stop further processing.
            return
        
        self.cleaned_data = {}
        # If the form is permitted to be empty, and none of the form data has
        # changed from the initial data, short circuit any validation.
        if self.empty_permitted and not self.has_changed():
            return
        
        # Don't run _post_clean() as this will run StockItem.clean()
        self._clean_fields()
        self._clean_form()

My models.py fileds:

part = models.ForeignKey('part.Part', on_delete=models.CASCADE,
                             related_name='stock_items', help_text=_('Base part'),
                             limit_choices_to={
                                 'is_template': False,
                                 'active': True,
                             })

    supplier_part = models.ForeignKey('company.SupplierPart', blank=True, null=True, on_delete=models.SET_NULL,
                                      help_text=_('Select a matching supplier part for this stock item'))

Yes, Django has the basics of a model-based permission system built-in.

Briefly, you would add the “create_part”, “create_supplier_part”, and “create_location” permissions to your users who need it. (Or, you could assign those permissions to a group, and then assign the appropriate users to that group.)

Then, within your view (or your form), you use the user.has_perm function to tell whether or not the user has those permissions.

(The way that we do it is that we define the form without the buttons, but with placeholders in the template. If a user is able to use a certain button, we add it to the context to be rendered. This means we’re not modifying the form, we’re just adding context in the view.)

I’m sure there are other ways of doing this as well…

Ken