Python/Django Dynamic Form creation
I have an html page, which have dropdown field. I had load dropdown values from DB. Now selecting dropdown, the required fields related to value may be load, which has been described in 1 DB Table. so how is it possible?
I have done like this...
class VenDocMastForm(forms.ModelForm):
doc_cat = forms.ChoiceField(
label='Document Type*',
choices=[(0, 'SELECT')] + [(dt.doc_type_id, dt.doc_type_desc) for dt in ven_doc_mast.objects.all()],
widget=forms.Select(attrs={'class': 'col-sm-12 form-control-sm dropdown'})
ven_doc_path = forms.FileField(
label='Upload Document File',
required=False, # This can be set to True if file upload is mandatory
widget=forms.ClearableFileInput(attrs={'class': 'form-control btn-outline-primary'})
)
class Meta:
model = ven_doc_hdr # Model used for saving data
fields = [
'doc_id',
'ven_id',
'doc_reg_no',
'doc_reg_dt',
'doc_last_dt',
'doc_reg_cat',
]
widgets = {
'doc_id': forms.NumberInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Document Type ID'}),
'ven_id': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Vendor ID'}),
'doc_reg_no': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Registration Number'}),
'doc_reg_dt': forms.DateInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'type': 'date'}),
'doc_last_dt': forms.DateInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'type': 'date'}),
'doc_reg_cat': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Registration Category'}),
}
def save(self, commit=True):
# Handle form saving to ven_doc_hdr
instance = super().save(commit=False)
# Save ven_doc_dtl entry if file is uploaded
if self.cleaned_data.get('ven_doc_path'):
ven_doc_dtl_instance = ven_doc_dtl(
doc_id=instance.doc_id,
ven_doc_type_id=instance.doc_id, # Example: Mapping the document type ID from ven_doc_hdr
ven_doc_path=self.cleaned_data['ven_doc_path'],
flag_un_di=0, # Default value
entered_mode='I', # Example, set as per your system
entered_user='current_user', # Example, replace with actual user
entered_ip='127.0.0.1' # Example, replace with actual IP
)
ven_doc_dtl_instance.save()
# If 'doc_cat' is used only for selection, it won't be saved
# Add any additional logic if necessary
if commit:
instance.save()
return instance
I have done with html, JavaScript and Views, without using Forms. Now I want to do it using Forms, so I could make it fully dynamic.
from .forms import VenDocMastForm
def add_ven_doc_mast_view(request):
# if request.method == "POST":
# form = VenDocMastForm(request.POST)
# if form.is_valid():
# form.save()
# return render(request, 'success.html', {'message': 'Record added successfully!'})
# else:
form = VenDocMastForm()
return render(request, 'ven_doc_mast_form.html', {'form': form})