blogApp – Forms and database connection Django by Ravinder Nath Rajotiya - January 5, 2022January 5, 20220 Share on Facebook Share Send email Mail Print Print Table of Contents Toggle blogApp – Forms and database connectionStep-1: Create forms.py and define the fields for tableStep-2: Modify the views.pyStep-3: Now modify the home page (index.html)Errors:Now restart the server by usingHow to Delete an item from DatabaseUpdate url.pyupdate views.pyUpdate index.html our home page blogApp – Forms and database connection In this post we are going to see how to connect forms with database in Django. We explain step by step method. Refer to previous post Simple blogApp in Django This post is extension of Simple blogApp in Django. The following files are created/updated Step-1: Create forms.py and define the fields for table from django import forms from .models import blogPostDb class blogposts(forms.ModelForm): class Meta: model = blogPostDb fields = [‘title’, ‘author’, ‘contents’] Step-2: Modify the views.py from django.shortcuts import render, redirect from .models import blogPostDb from .forms import blogposts from django.contrib import messages # Create your views here. def home(request): if request.method == ‘POST’: form = blogposts(request.POST or None) if form.is_valid(): form.save() all_posts=blogPostDb.objects.all() messages.success(request,(‘Post added…..’)) return render(request, ‘blog/index.html’, {‘all_posts’: all_posts}) else: all_posts=blogPostDb.objects.all() return render(request, ‘blog/index.html’, {‘all_posts’: all_posts}) Step-3: Now modify the home page (index.html) <!DOCTYPE html> <html lang=”en” dir=”ltr”> <head> <meta charset=”utf-8″> <title></title> </head> <body> <h1>Welcome home</h1> {% for posts in all_posts %} <h1>{{posts.title}}</h1> <p>BY {{posts.author}} on {{ posts.date_post }}</p> <p>{{posts.contents}}</p> {% endfor %} <h1>Form entry for blog</h1> <form action=”{% url ‘home’ %}” method=”post”> {% csrf_token %} <input type=”text” name=”title” placeholder=”Enter title”> <br> <input type=”text” name=”author” placeholder=”Enter author name”> <br> <input type=”text” name=”contents” placeholder=”Enter contents”> <br> <input type=”submit” value=”Click me to Submit”> <br> {% if messages %} {% for message in messages %} {{message}} {% endfor %} {% endif %} </form> </body> </html> Errors: The error appears because there is no table yet in the database. All you have to do is go to terminal, exit the server by “CTRL + ‘C’ ” and then using the following commands (venv) E:\project\webAppProjects\formProject> python manage.py makemigrations Migrations for ‘formApp’: formApp\migrations\0001_initial.py – Create model blogaDataDb (venv) E:\project\webAppProjects\formProject>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, formApp, sessions Running migrations: Applying contenttypes.0001_initial… OK this will create the table formAll.blogDataDb Now restart the server by using (venv) E:\project\webAppProjects\formProject>python manage.py runserver refresh the browser to see the page functioning How to Delete an item from Database here we will modify our views.py, url.py and index.html for deleting an item. Update url.py from django.urls import path from . import views urlpatterns = [ path(”, views.home, name=’home’), path(‘delete/<list_id’, views.delete, name=’delete’) ] update views.py Now create a delete function in views.py and update the following code. def delete(request, list_id): item=blogaDataDb.objects.get(pk=list_id) # creates an ‘item’ object from database item.delete() #delete the object with id =pk messages.success(request,(‘ Post deleted successfully’)) # display successful operation return redirect(‘home’) # redirect to home page Update index.html our home page <h2>Blog posts are here</h2> {% for i in all_posts %} <h1>{{i.title}}</h1> <p>Contents: {{ i.contents }} <a href=”{% url ‘delete’ i.id %}“>Delete This ?</a> </p> {% endfor %} Now refresh the browser you will find a page with delete anchor for delete operation and cilck me button for adding posts as : Share on Facebook Share Send email Mail Print Print