About Lesson
Creating a Simple Form
-
- Define the Form Class: In your app’s
forms.py
file, define a form class that inherits fromforms.Form
:from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea)
CharField
: A basic text field.EmailField
: A field that validates email input.Textarea
: A widget for multi-line text input.
- Rendering the Form in a Template: In the view, pass the form to the template:
from django.shortcuts import render from .forms import ContactForm def contact_view(request): form = ContactForm() return render(request, 'contact.html', {'form': form})
In
contact.html
, render the form:
<form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Send</button> </form>
- Define the Form Class: In your app’s
Join the conversation