How To Work With Django Forms.
- Shivam Rohilla
- May 28, 2022
- 3 comments
- 440 Views
<meta name="clckd" content="6301244fb7ed470eb1cd6b8c31d01ac4" />
Hello guys, today we'll learn how to work with Django forms, as we know that we use Django forms to save data in the models, Django forms generate the HTML Forms to save the data, and Django provides the Form class that is used to generate HTML form.
Source code:- https://github.com/ShivamRohilllaa/django-form
So, now we are creating a Django form, in forms.py
from django import forms
class TaskForm(forms.Form):
Title = forms.CharField(max_length = 200)
description = forms.TextField(max_length = 500)
now write a view for saving the data.
from django.shortcuts import render, redirect
from .forms import TaskForm
from .models import Task
# Create your views here.
def index(request):
tform = TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
description = form.cleaned_data['description']
data = Task.objects.create(title=title, description=description)
context = {'form':tform}
return render(request, 'index.html', context)
then render this form in index.html
<form method='POST'>
{% csrf_token %}
{{form}}
<button class="btn" type="submit" value="submit"> Save </button>
</form>
See the output below and fill the data in form and then press save button after that check the django admin if data is saved or not.
Thank You
Shivam Rohilla | Python Developer
My social media links