
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Form Widget in Django
In this article, we will see how to use widgets in a Django form. Widgets can be quiet helpful to make the frontend better. Widgets are html elements that are rendered from Django form, textarea, input, password input, etc., all are widgets.
First let's create a Django project and an app. I created the project with the name "tutorial14" and app with the name "djangoFormWidget".
Add app in settings.py and include app's URL in project urls.py.
Make every basic files and folders like Templates, home.html, forms.py.
Example
In app's urls.py −
from django.urls import path,include from . import views urlpatterns = [ path('',views.home,name="home") ]
It will create a basic URL for rendering view.
In views.py −
from django.shortcuts import render from .forms import CommentForm # Create your views here. from django.views.decorators.csrf import csrf_exempt @csrf_exempt def home(request): if request.method=='POST': form=CommentForm(request.POST) if form.is_valid(): form.save() commentform=CommentForm() return render(request,'home.html',{"commentform":commentform})
Here, we imported our form and handled its POST and GET requests.
In POST, we save the data and in GET, we send the form to the frontend.
In models.py −
from django.db import models # Create your models here. class CommentModel(models.Model): comment=models.CharField(max_length=500)
Here we created a model which we will use in our form. We need this model to use the form.
In home.html −
<!DOCTYPE html> <html> <head> <title>TUT</title> </head> <body> {% for fm in commentform %} <form method="post"> {%csrf_token%} {{fm.errors}}<br> {{fm.label}}:{{fm}}<br> {%endfor%} <button type="submit">Submit</button> </form> </body> </html>
It is a simple frontend where we render our form.
In forms.py −
from django import forms from .models import CommentModel class CommentForm(forms.Form): comment=forms.CharField(widget=forms.Textarea(attrs={'class':'comment','title':'add comment'})) # this is the line which is used for widget, here I added TextArea widget you can see we also assigned class to widget using attrs attribute. def save(self): data=self.data modelRef=CommentModel(comment=data['comment']) modelRef.save()
It is where we make our form. We used the built-in Django form widget to render a textarea in the form.