Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 26, 2022 08:19 pm GMT

Creating Forms in Django

Hi guy's today i am going to show you how can we create forms in django

Step 1 : Setting up the django Project

Image description

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

Image description

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)

  1. 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 formsfrom django.core.validators import MaxLengthValidatorclass 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

  1. now lets create a view in views.py which will render the form
# views.pyfrom .forms import ContactFormdef 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 projectfrom django.contrib import adminfrom django.urls import pathfrom demo.views import contact_formurlpatterns = [    path('admin/', admin.site.urls),    path('', contact_form),]
  1. rendering the form in form.html

there are two ways to render the form in our template

  1. 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

Image description

handling the data submitted by the form

from django.shortcuts import render# Create your views here.from .forms import ContactFormdef 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 terminalMarch 26, 2022 - 20:06:02Django 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 [**][email protected]

but when the data entered in the forms is incorrect the error message is displayed

Image description

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>

Original Link: https://dev.to/rohit20001221/creating-forms-in-django-5797

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To