Working With Django Model Forms

 

Model Forms (Forms based on Model):

1) Sometimes we can create form based on Model, such type of forms are called model

   based forms or model forms.

2) The main advantage of model forms is we can grab end user input and we can save

   that input data very easily to the database.

3) Django provides inbuilt support to develop model based forms very easily.

How to develop Model based Forms:

1) While develop FormClass instead of inheriting forms.Form class,we have to inherit

   forms.ModelForm class.

class RegisterForm(forms.ModelForm):

….

2) We have to write one nested class (Meta class) to specify Model information and

   required fields.

class RegisterForm(forms.ModelForm):

# field declarations if we are performing any custom validations.If we are not defining

any custom validations then here we are not required to specify any field.

class Meta:

# we have to specify Model class name and requied fields

model=Student

fields=’__all__’

Case-1: Instead of all fields if we want only selected fields, then we have to specify as

follows

class Meta:

model=Student

fileds=(‘field1′,’field2′,’field3’)

In the form only 3 fields will be considered.

If Model class contains huge number of fields and we required to consider very less

number of fields in the form then we should use this approach.

Case-2:

Instead of all fields if we want to exclude certain fields ,then we have to specify as follows

class Meta:

model=Student

exclude=[‘field1′,’field2’]

In the form all fields will be considered except field1 and field2.

If the Model class contains huge number of fields and if we want to exclude very few fields

then we have to use this approach.


Q) In Model based Forms, how many ways are there to

specify Fields Information 

Ans: 3 ways

                 1) All fields

                 2) Include certain fields

                 3) Exclude certain fields

Note: The most commonly used approach is to include all fields. 

How to Save User’s Input Data to Database in Model based Forms:

We have to use save() method.

def student_view(request):


       if request.method==’POST’:

              form=RegisterForm(request.POST)

              if form.is_valid():

                  form.save(commit=True)

.. 


Demo project-1 (modelformproject):

models.py:

          1) from django .db import models

         2)

         3)#Createyourmodelshere.

        4) class Student(models.Model):

        5) name=models.CharField(max_length=30)

        6) marks=models.IntegerField()

forms.py: 

 

         1) from django import forms

         2) from testapp .models import Student

         3) class StudentForm(forms.ModelForm):

        4) #fields with validations

        5) class Meta:

        6) model=Student

       7) fields=‘__all__’

views.py: 

       1) from django .shortcuts import render

      2) from .import forms

      3)

      4) #Create your views here.

     5) def student_view(request):

     6)         form=forms.StudentForm

    7)          if request.method==‘POST’:

    8)              form=forms.StudentForm(request.POST)

    9)               if form.is_valid():

   10)             form.save(commit=True)

   11)         return render(request,‘testapp/studentform.html’,{‘form’:form})

How to Add Date Widget:

write a DateInput class in forms.py as:

class DateInput(forms.DateInput):

input_type = ‘date’

class MoviesForm(forms.ModelForm):

movie_name =forms.CharField(widget=forms.TextInput(attrs={‘class’:’form-control’}))

release_date =forms.DateField(widget=DateInput(attrs={‘class’:’form-control’}))

hero_name =forms.CharField(widget=forms.TextInput(attrs={‘class’:’form-control’}))

heroine_name =forms.CharField(widget=forms.TextInput(attrs={‘class’:’form-control’}))

director_name =forms.CharField(widget=forms.TextInput(attrs={‘class’:’form-control’}))

movie_ratings =forms.FloatField(widget=forms.TextInput(attrs={‘class’:’form-control’}))

class Meta:

model=MoviesModel

fields=[‘movie_name’,’release_date’,’hero_name’,’heroine_name’,’director_name’,’movie

_ratings’]

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *