Model Forms in Django (How to save data using model and form)

Опубликовано: 16 Апрель 2023
на канале: Developer Bites
42
1

A model Form is a python class which is directly connected to model and helps in generating the required HTML form to facilitate the posting of the data by the user and easily saving it into the database.

At first, create a database model in models.py :

class Articles(models.Model):
"to save data in the articles table"
title = models.CharField(max_length=150)
description = models.TextField()
created_by = models.CharField(max_length=150)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.title

class Meta:
db_table = 'articles'


Create a file forms.py in your app and define the model form class like this:

from .models import Articles
from django import forms

class ArticlesForm(forms.ModelForm):
"to save data into the database using articles form"
class Meta:
model = Articles
fields = ('title','description')

In the file views.py, type code like this:

from .forms import ArticlesForm

def create_article(request):
"to create articles"
if request.method=='POST':
form = ArticlesForm(request.POST)
if form.is_valid():
article = form.save(commit=False)
article.created_by = request.user
article.save()
return redirect(reverse('create_success'))
else:
return render(request, "test1_app/create_article.html", {'form':form})
form = ArticlesForm()
return render(request, "test1_app/create_article.html", {'form':form})



Please watch the video carefully to grasp the concept completely.