0Pricing
Django Academy · Lección

Definir un forms.Form

Declare campos y sus widgets

Definir un forms.Form es una lección gratuita de Django Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Django Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Django Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Forms Exist

A Django form turns messy user input into clean Python data, handling rendering and validation in one tidy place. 📝

Subclass forms.Form

You declare a form by subclassing forms.Form. Each class attribute you add becomes a field on that form.

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField()

Fields Are Class Attributes

Every field is a class attribute set to a field instance, like CharField or EmailField. The attribute name becomes the input name.

name = forms.CharField()
email = forms.EmailField()

CharField for Text

Use CharField for short text. Set max_length to cap the size and render a sensible HTML input automatically.

subject = forms.CharField(max_length=120)

EmailField Validates Format

An EmailField checks that the value looks like a real email address, so you do not write that validation yourself.

email = forms.EmailField()

Required by Default

Every field is required unless you say otherwise. Pass required=False to make a field optional for the user.

phone = forms.CharField(required=False)

label and help_text

Add a friendly label and help_text so users understand each field. Django shows them next to the input.

name = forms.CharField(label="Your name",
    help_text="First and last")

Choosing a Widget

A widget controls the HTML rendered for a field. Swap the default to get a textarea, password box, or select.

message = forms.CharField(
    widget=forms.Textarea)

More Field Types

Django ships many fields: IntegerField, BooleanField, DateField, and ChoiceField each map to the right input and parse the value for you.

age = forms.IntegerField()
agree = forms.BooleanField()

ChoiceField and Options

A ChoiceField renders a dropdown from a list of value and label pairs you provide in choices.

plan = forms.ChoiceField(choices=[
    ("free", "Free"), ("pro", "Pro")])

Instantiate the Form

Create an unbound form with no data to display a blank form, or pass data to bind it for validation.

form = ContactForm()  # blank
form = ContactForm(request.POST)

Quick Check

Let us see how forms are defined.

Recap

You subclass forms.Form and add fields as class attributes. Pick the right field type and widget, and Django handles the rest. ✅

Preguntas frecuentes

¿La lección «Definir un forms.Form» es gratis?

Sí — el texto completo de «Definir un forms.Form» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Django Academy, actualiza a CoddyKit PRO. El curso de Django Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Definir un forms.Form»?

Declare campos y sus widgets Practicas Django Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Django Academy?

No se requiere experiencia previa. Django Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.

¿Cuánto tiempo toma la lección «Definir un forms.Form»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Django Academy?

Sí. Cada lección de Django Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Definir un forms.Form
  2. is_valid y cleaned_data
  3. Renderizar formularios en plantillas
  4. Protección CSRF y flujo POST
← Volver a Django Academy