Hi guy's today i am going to show you how can we create forms in django
Step 1 : Setting up the django Project
create a django project using the following command
django-admin startproject DjangoForms
Step 2 : Creating a app in our project
- fist
cd
into your project directory and type the following command
python manage.py startapp demo
Step 3 : Creating Forms 😄
creating a normal form
first let me show how to create a normal form (i.e this form is not connected to any of the models)
- create a file called
forms.py
in your app folder
we will be importing the froms from django using following code
from django import forms
every form in django will inherit the following class
forms.Form
for example we will create a form called ContactForm as follows
class ContactForm(forms.Form)
now lets add some fileds to our form
from django import forms
from django.core.validators import MaxLengthValidator
class ContactForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
mobile = forms.CharField(
validators=[MaxLengthValidator(10)]
)
we can use form.TypeField for the fields Type can be anything like Char, Email, Integer,Float etc ...
and also note that we are adding MaxLengthValidator to the validators of mobile field this ensures that when the form is submitted the length of value of mobile field is less than 10
-
now lets create a view in
views.py
which will render the form
# views.py
from .forms import ContactForm
def contact_form(request):
form = ContactForm() # <-- Initializing the form
# sending the form to our template through context
return render(request, "form.html", {"contactform": form})
mapping the view to the urls.py
# urls.py of the project
from django.contrib import admin
from django.urls import path
from demo.views import contact_form
urlpatterns = [
path('admin/', admin.site.urls),
path('', contact_form),
]
- rendering the form in
form.html
there are two ways to render the form in our template
- rendering using
form.as_p
<form method="POST" action="">
{{form.as_p}}
<button>submit</button>
</form>
run the development server using python manage.py runserver
if you navigate to http://localhost:8000
the form is displayed as shown below
handling the data submitted by the form
from django.shortcuts import render
# Create your views here.
from .forms import ContactForm
def contact_form(request):
form = ContactForm() # <-- Initializing the form
if request.method == 'POST':
form = ContactForm(request.POST) # <-- populating the form with POST DATA
if form.is_valid(): # <-- if the form is valid
print("[**] data received [**]") # <-- we handle the data
print(form.cleaned_data['name'])
print(form.cleaned_data['email'])
print(form.cleaned_data['mobile'])
# sending the form to our template through context
return render(request, "form.html", {"contactform": form})
When the form is submitted successfully we see the data logged to terminal
# output in the terminal
March 26, 2022 - 20:06:02
Django version 3.0.7, using settings 'DjangoForms.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[**] data received [**]
blog
rohit20001221@gmail.com
9999999999
but when the data entered in the forms is incorrect the error message is displayed
we can see the mobile number is more than 10 characters long so the error message is displayed in the form
Alternate way to render a form
render each field manually
<form method="POST" action="">{% csrf_token %}
<div>
{{ form.name }}
<!---Rendering the error message--->
{% for error in form.name.error %}
{{error}}
{% endfor %}
</div>
<div>
{{ form.email }}
<!---Rendering the error message--->
{% for error in form.email.error %}
{{error}}
{% endfor %}
</div>
<div>
{{ form.phone }}
<!---Rendering the error message--->
{% for error in form.phone.error %}
{{error}}
{% endfor %}
</div>
<button>submit</button>
</form>
Top comments (0)