Django Crispy forms, Random Requirements.

Django has wide range of plugins which reduces the development time, One of them is Django Crispy forms this helps developers to convert their Django forms into complete bootstrap 3/4 , Uni-form or foundation UI template styles.

There are many customizations which can be done to your crispy forms lets go through them one by one.

1. Passing arguments to your django froms

There might come a situation where you want to pass some arguments to forms to check them for some value and enable some fields, or you may want to set some pre-defined values to your inputs from the request parameters.

#Forms
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class SomeForm(forms.ModelForm):
  def __init__(self, *args, **kwargs):
    self.name_required = kwargs.pop('name_required',False)# value passed to forms to check name should be required or not
    self.helper = FormHelper()
    super(SomeForm, self).__init__(*args, **kwargs)
    self.fields['name'].required = True if self.name_required else False
    class Meta:
      model = SubCategoriesList
      fields = ('name','mobile')

#Views
from django.views import View
from .forms import SomeForm
class SomeView(View):
  def get(self,request):
    name_required = request.GET.get('name_required')
    form = SomeForm(name_required=name_required)
    return render(request,'some.html',{'form':form})

2. Adding FORM Tag attributes

Lets say you want to add FORM tag attributes like ID, Class, ACTION etc to your form elements.

class SomeForm(forms.ModelForm):
  def __init__(self, *args, **kwargs):
    self.helper = FormHelper()
    super(SomeForm, self).__init__(*args, **kwargs)
    self.helper.form_action = '/somepage/' #-> <form action="/somepage/">

Providing Form ID, Class and Method

self.helper.form_id = "dynamicform" # -> <form id="dynamicform">
self.helper.form_class= "form-horizontal" #-> <form class="form-horizontal">
self.helper.form_method = "post" #-> <form method="post">

Providing custom set of attributes to the form tag

self.helper.attrs = {'autocomplete': 'off','data-parsley-validate': 1} #-> <form autocomplete="off" data-parsley-validate>

Enable or disable form tag

self.helper.form_tag = False

Add submit button to your form

self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary',css_id='submit-id'))

3. Adding tag attributes to form elements

Now lets add some attributes to form input elements such as Input Field, Textarea, DateFields etc.

self.fields['mobile'].widget.attrs['pattern']="^[6789]\d{9}$" #-> <input type="text" pattern="^[6789]\d{9}$"/>
self.fields['mobile'].widget.attrs['id']="mobile_number" #-><input type="text" id="mobile_number"/>

59 total views, 3 views today

Posts created 6

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top