<meta name="clckd" content="6301244fb7ed470eb1cd6b8c31d01ac4" />
Django

How To Work With Django Forms.

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.

Output

Image description

Image description

Thank You
Shivam Rohilla | Python Developer

0 Comments
  • No Reviews Yet

Leave a Reply
Please Sign In For Comment.
Login or Signup
Shivam Rohilla
Hi, I'm Shivam Rohilla

Hi! My name is Shivam Rohilla. I am a Full Stack Web Developer, and I'm very passionate and dedicated to my work. With 2 years experience as a professional Full Stack Web Developer.

Follow Me:-

My social media links