Episode 7 of 13

New Contact Form

Learn about New Contact Form

Django Forms Overview

Django provides a powerful forms module that handles everything from rendering HTML form fields to validating user input and displaying error messages. Instead of manually writing form HTML, you define a form class in Python and Django generates the markup for you.

Creating a ModelForm

In the contacts app, create a new file called forms.py. Import ModelForm from django.forms and your Contact model. Define a ContactForm class that inherits from ModelForm. Inside the Meta class, set the model to Contact and list all the fields you want to include: first_name, last_name, email, phone, and photo.

Customizing Form Widgets

Override the default widgets in the Meta class to add CSS classes to each input field. This allows you to apply DaisyUI's "input input-bordered" classes directly to the rendered inputs so they match your design system. You can also set placeholder text and other HTML attributes through the widgets dictionary.

Creating the Form View

In views.py, create a new view called create_contact. For GET requests, instantiate an empty ContactForm and pass it to the template. For POST requests, instantiate the form with the submitted data (request.POST and request.FILES for file uploads), call form.is_valid(), and if valid, call form.save() to create the new contact in the database.

Building the Form Template

Create a template that renders the form. Use the form object to output each field individually for full control over the layout. Wrap each field in a div with a label element for accessibility. Include a CSRF token using the csrf_token template tag — Django requires this for all POST requests as a security measure.

Adding the URL

Add a URL pattern that maps a path like "new/" to the create_contact view. Add a link or button on the contact list page that navigates to this new form page.