We will use Django form class to create the form and then use it.
We will create one form.py file with this code.
form.py
from django import forms
# creating a form
class my_form(forms.Form):
id = forms.IntegerField(label='id here',required=False)
name = forms.CharField(label='Your name',required=False)
Inside views.py I will import the form like this.
views.py
from .forms import my_form
Inside this views.py file we will have function suggest() like this
def suggest(request):
str1=request.POST.get('name') # collect the name filed data
id=request.POST.get('id') # collect the id field data
form = my_form(request.POST) # the from
if form.is_valid():
return render(request,'suggest.html',{'form':form,'name':str1,'id':id})
else:
return render(request,'suggest.html',{'form':form})
Our file suggest.html file gets the form and the output ( both )
We can add one dropdown listbox by using ChoiceField. We created one list and same is attached to ChoiceField by choices option.
forms.py
from django import forms
l1=[(1,'One'),(2,'Two'),(3,'Three')]
# creating a form
class my_form(forms.Form):
id = forms.IntegerField(label='id here',required=False)
name = forms.CharField(label='Your name',required=False)
cl=forms.ChoiceField(choices=l1,required=False)
Out of the three options available, we will keep the third choice or option default selected. ( watch initial={"cl":3} )
views.py
def my_dd(request):
form = my_form(request.POST or None, initial={"cl": 3})
if form.is_valid():
cl=request.POST.get('cl')
name=request.POST.get('name')
id=request.POST.get('id')
return render(request,'dd.html',{'form':form,'cl':cl,'id':id,'name':name})
else:
return render(request,'dd.html',{'form':form})
We can add Checkbox to the form by using BooleanField.
forms.py
from django import forms
l1=[(1,'One'),(2,'Two'),(3,'Three')]
# creating a form
class my_form(forms.Form):
id = forms.IntegerField(label='id',required=False)
name = forms.CharField(label='Name',required=False)
cl=forms.ChoiceField(choices=l1,required=False)
ckb = forms.BooleanField(initial=True,required=False)
Inside views.py we will set the initial value of the checkbox to True or False.
views.py
def my_dd(request):
form = my_form(request.POST or None, initial={"cl": 3,'ckb':True})
if form.is_valid():
cl=request.POST.get('cl')
name=request.POST.get('name')
id=request.POST.get('id')
ckb=request.POST.get('ckb')
return render(request,'dd.html',{'form':form,'cl':cl,'id':id,'name':name,'ckb':ckb})
else:
return render(request,'dd.html',{'form':form})