DEV Community

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

Posted on

3 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
zodman profile image
Andres 🐍 in 🇨🇦

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay