DEV Community

Cover image for How to work with Django forms.
Shivam Rohilla
Shivam Rohilla

Posted on

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, django provides the Form class that is used to generate html form.

Source code:- https://github.com/ShivamRohilllaa/django-form
Enter fullscreen mode Exit fullscreen mode

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)   

Enter fullscreen mode Exit fullscreen mode

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)


Enter fullscreen mode Exit fullscreen mode

then render this form in index.html

    <form method='POST'>
    {% csrf_token %}    
    {{form}}
    <button class="btn" type="submit" value="submit"> Save </button>
    </form>

Enter fullscreen mode Exit fullscreen mode

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

For More and contact:- https://webdevcodes.com/django/how-to-work-with-django-forms/ 

Enter fullscreen mode Exit fullscreen mode

Thank You
Shivam Rohilla | Python Developer

Discussion (1)

Collapse
zodman profile image
Andres 🐍 in 🇨🇦

and if you mix with htmx uff you are now a fullstack!