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, 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.
Output
For More and contact:- https://webdevcodes.com/django/how-to-work-with-django-forms/
Thank You
Shivam Rohilla | Python Developer
Top comments (1)
and if you mix with htmx uff you are now a fullstack!