Fundamentos de Django
¿Qué es Django?
¿Cómo instalar Django?
Entendiendo la arquitectura de Django
Qué es el patrón MVT (Model, View y Template)
La M en el Patrón: Modelo
Introducción a Modelos y Bases de Datos
Manejo Avanzado de Modelos y Bases de Datos
Gestión de Modelos y Bases de Datos en Django con SQLite
Inserción de Datos con Django
Actualización y Eliminación de Datos en Django
Relaciones y Asociaciones entre Modelos
Creación y Gestión de Relaciones entre Modelos en Django
Relaciones Muchos a Muchos (N:N) en Django
Relaciones Uno a Uno (1:1) en Django
Queries y Filtros en Django: Optimización y Estrategias Avanzadas
Configuración de URLs y Vistas Avanzadas
Gestión de URLs en Django: Configuración, Rutas y Mejores Prácticas
Vistas Basadas en Clases en Django
La T en el Patrón: Plantillas o Templates
Personalización de Interfaz con Plantillas en Django
Desarrollo de Aplicaciones en Django
Configuración del Proyectos en Django
Creación del Modelo para la Aplicación 'Products' en Django
Cómo Crear Migraciones de Datos en Django
Creación de la Aplicación 'Products' con Formularios en Django
Integracion de TailwindCSS en Django
Django Admin
Manejo de Sesiones en Django
Manejo de Órdenes en CoffeShop
Manejo de Pedidos en CoffeShop
Mixings en vistas basadas en clases
Agregar productos a la orden
Django Rest Framework
Django REST Framework
Despliegue de aplicaciones Django
Configurar PostgreSQL en AWS con Django
Variables de entorno en Django
¿Cómo usar Unit Testing en Django?
Debugging en Django
Desplegar aplicaciones de Django en AWS
You don't have access to this class
Keep learning! Join and start boosting your career
The forms functionality in Django allows developers to create, validate and manage forms in an efficient and organized way. Below, we will explore how to create forms in Django step by step.
To create a new form in Django, you must first create a class that inherits from forms.Form.
This class will contain all the fields we want to include in the form.
from django import formsclass ProductForm(forms.Form):name = forms.CharField(max_length=200, label='Name') description = forms.CharField(max_length=300, label='Description') price = forms.DecimalField(max_digits=10, decimal_places=2, label='Price') available = forms.BooleanField(initial=True, label='Available', required=False) photo = forms.ImageField(label='Photo', required=False)
Once the form is created, we need to define how to handle the data when the user submits the form. This includes validating the data and saving it to the database.
def save(self): from.models import Product data = self.cleaned_data Product.objects.create( name=data['name'], description=data['description'], price=data['price'], available=data['available'], photo=data['photo'] )
The view connects the form with the template and handles the user request. We will use a generic Django view to simplify this process.
from django.views.generic.edit import FormViewfrom django.urls import reverse_lazyfrom.forms import ProductFormclass ProductFormView(FormView):template_name = 'products/add_product.html'form_class = ProductForm success_url = reverse_lazy('product_list') def form_valid(self, form):form.save() return super().form_valid(form)
You need to configure the URLs for the view to be accessible from the browser.
from django.urls import pathfrom.views import ProductFormView urlpatterns = [ path('add/', ProductFormView.as_view(), name='add_product') ]
The template defines the HTML structure of the form and how it is rendered on the web page.
:<h1>AddProduct</h1><form method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button type="submit">Add</button></form>.
The CSRF token is a security measure that protects against Cross-Site Request Forgery attacks. Django automatically includes it in forms to ensure that requests come from trusted sources.
Redirection after form submission is handled by setting the success_url
parameter in the view, using reverse_lazy
to get the destination URL.
When the form is valid, the form_valid
method is in charge of calling the save
method of the form to save the product in the database.
Contributions 20
Questions 9
` elements), where each form field is wrapped in its own paragraph. This is a convenient way to quickly generate an HTML form without having to manually write the HTML for each field. Here's a breakdown of how it works: ### Usage When you use `{{ form.as_p }}` in a Django template, Django automatically generates the HTML for the form, including the form fields and their labels, wrapped in `
` tags. This is particularly useful for simple forms where you want a quick and easy way to render the form fields.
Want to see more contributions, questions and answers from the community?