Django Model Form

It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code.

Django automatically does it for us to reduce the application development time. For example, suppose we have a model containing various fields, we don't need to repeat the fields in the form file.

For this reason, Django provides a helper class which allows us to create a Form class from a Django model.

Let's see an example.

Django ModelForm Example

First, create a model that contains fields name and other metadata. It can be used to create a table in database and dynamic HTML form.

// model.py

This file contains a class that inherits ModelForm and mention the model name for which HTML form is created.

// form.py

Write a view function to load the ModelForm from forms.py.

//views.py

//urls.py

And finally, create a index.html file that contains the following code.

Run Server

Run the server by using python manage.py runserver command.

After that access the template by localhost:8000/index URL, and it will produce the following output to the browser.

Output:

django model form

Well, an HTML form is created automatically. This is a feature of Django.


Next TopicDjango Forms




Contact US

Email:[email protected]

ModelForms
10/30