Django Python Create Forms From Models With ModelForm Example

Published On: 27/06/2022 | Category: Django Python

This article will give you example of django python create forms from models with modelform. This article goes in detailed on django python create forms from models with modelform all fields. we will help you to give example of django python create forms from models with modelform app. it's simple example of django python create forms from models with modelform example.

So, Django ModelForm is a class that is used to directly convert a model into a Django form.

Let's see bellow example we will implement a django python create forms from models with modelform example.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject exampleapp
Step 2 : Create a App
python3 manage.py startapp blog

Next, you need to add it in the settings.py file as follows:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]
Step 3 : Create a Model

In this step create a model and map it to Django forms.Now when we have our project ready, create a model in blog/models.py.

from django.db import models

# declare a new model with a name "BlogModel"
class BlogModel(models.Model):
        # fields of the model
    title = models.CharField(max_length = 200)
    description = models.TextField()
    last_modified = models.DateTimeField(auto_now_add = True)

        # renames the instances of the model
        # with their title name
    def __str__(self):
        return self.title

Now run the bellow command to migrate your model.

python manage.py makemigrations
python manage.py migrate
Step 4 : Create a FormClass

Next in this section to create a form directly for this model, dive into blog/forms.py and Enter following code,

blog/forms.py
from django import forms

# import BlogModel from models.py
from .models import BlogModel

# create a ModelForm
class BlogForm(forms.ModelForm):
    # specify the name of model to use
    class Meta:
        model = BlogModel
        fields = "__all__"
Step 5 : Creating the Views

Now to render this form we need to create the view and template which will be used to display the form. In blog/views.py, create a view

blog/views.py
from django.shortcuts import render
from .forms import BlogForm

def home_view(request):
    context ={}

    # create object of form
    form = BlogForm(request.POST or None)
    
    # check if form data is valid
    if form.is_valid():
        # save the form data to model
        form.save()

    context['form']= form
    return render(request, "home.html", context)
Step 6 : Creating the Template

Next, open the home.html file and the add:

<h2>Django Python Create Forms From Models With ModelForm - Tuts-Station.com</h2>

<form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit">
</form>
Step 7 : Creating Urls

In this section, we’ll create the urls to access our views.Go to the urls.py blog/urls.py file and update it as follows:

blog/urls.py
from django.urls import path
from blog import views

urlpatterns = [
    path('', views.home_view),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

exampleapp/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]

Now let’s display the form by running

python manage.py runserver
Output