Forms Basics

Back

Loading concept...

Django Forms Basics: Building Your Digital Order Form 📝


The Big Picture: What Are Django Forms?

Imagine you’re running a pizza shop. Customers walk in and tell you what they want. But sometimes they forget toppings, give wrong phone numbers, or mumble their orders. Chaos!

What if you had a perfect order form? One that:

  • Has boxes for name, phone, pizza size
  • Checks if the phone number looks real
  • Won’t let them submit without filling required fields

That’s exactly what Django Forms do for websites!

Django Forms are like smart paper forms that:

  1. Collect information from users (text, numbers, choices)
  2. Check if it’s valid (Is that really an email? Is the date in the future?)
  3. Clean up the data (trim spaces, format dates)
  4. Make it safe (protect against hackers)

🏗️ Forms Overview: The Control Center

Think of a Django Form as a blueprint for collecting information.

graph TD A["User Opens Page"] --> B["Django Shows Form"] B --> C["User Fills Fields"] C --> D["User Clicks Submit"] D --> E{Form Checks Data} E -->|Valid| F["Save & Process"] E -->|Invalid| G["Show Errors"] G --> C

Why Use Django Forms?

Without Forms With Forms
Write HTML manually Auto-generate HTML
Check data yourself Automatic validation
Risk security holes Built-in protection
Handle errors yourself Automatic error messages

Real Example: A contact form that collects name and email.

# Without Django Forms (messy!)
name = request.POST.get('name', '')
email = request.POST.get('email', '')
# Now you check if email is valid...
# Check if name is not empty...
# Escape dangerous characters...
# So much work!

# With Django Forms (clean!)
form = ContactForm(request.POST)
if form.is_valid():
    name = form.cleaned_data['name']
    email = form.cleaned_data['email']
    # Done! Already validated & safe!

🎨 Form Class Definition: Your Form Blueprint

Creating a form is like designing a paper form, but in Python code.

Basic Structure

from django import forms

class PizzaOrderForm(forms.Form):
    customer_name = forms.CharField()
    phone = forms.CharField()
    quantity = forms.IntegerField()

Breaking it down:

  1. Import forms - Get Django’s form tools
  2. Create a class - Name it SomethingForm
  3. Inherit from forms.Form - Get all the magic
  4. Add fields - Each line = one input box

Using Your Form

# In your view
def order_pizza(request):
    if request.method == 'POST':
        form = PizzaOrderForm(request.POST)
        if form.is_valid():
            # Data is clean and safe!
            name = form.cleaned_data['customer_name']
            print(f"Order from {name}!")
    else:
        form = PizzaOrderForm()  # Empty form

    return render(request, 'order.html',
                  {'form': form})

In Your Template

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Order!</button>
</form>

Magic! Django creates all the HTML input boxes automatically.


📝 Common Form Fields: The Basic Building Blocks

These are the fields you’ll use 90% of the time.

CharField - For Text

Like a blank line on a paper form.

class ContactForm(forms.Form):
    # Simple text input
    name = forms.CharField()

    # With max length (like a box with 50 spaces)
    username = forms.CharField(max_length=50)

    # Multi-line text (like a big box)
    message = forms.CharField(
        widget=forms.Textarea
    )

    # Optional field
    nickname = forms.CharField(required=False)

EmailField - For Email Addresses

Automatically checks if it looks like an email!

class SignupForm(forms.Form):
    email = forms.EmailField()
    # Will reject "hello"
    # Will accept "hello@example.com"

IntegerField - For Whole Numbers

Like asking “How many?” with number boxes.

class OrderForm(forms.Form):
    quantity = forms.IntegerField()

    # With limits
    age = forms.IntegerField(
        min_value=0,
        max_value=120
    )

DecimalField - For Prices and Precise Numbers

When you need exact decimal numbers (like money).

class ProductForm(forms.Form):
    price = forms.DecimalField(
        max_digits=10,    # Total digits
        decimal_places=2  # After the dot
    )
    # Accepts: 99.99, 1234.50

BooleanField - For Yes/No Questions

Like a checkbox on a paper form.

class AgreementForm(forms.Form):
    # Must check to submit (required)
    accept_terms = forms.BooleanField()

    # Optional checkbox
    subscribe = forms.BooleanField(required=False)

URLField - For Website Links

Checks if it’s a real-looking URL.

class ProfileForm(forms.Form):
    website = forms.URLField(required=False)
    # Accepts: https://example.com
    # Rejects: just some text

🎯 Choice Form Fields: Pick One (or More!)

Like multiple choice questions on a test.

ChoiceField - Pick ONE Option

class SurveyForm(forms.Form):
    SHIRT_SIZES = [
        ('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
        ('XL', 'Extra Large'),
    ]

    size = forms.ChoiceField(choices=SHIRT_SIZES)

How choices work:

  • First value ('S') = what’s saved
  • Second value ('Small') = what user sees
graph TD A["ChoiceField"] --> B["Dropdown Menu"] A --> C["Radio Buttons"] B --> D["Select one option"] C --> D

Radio Buttons Instead of Dropdown

size = forms.ChoiceField(
    choices=SHIRT_SIZES,
    widget=forms.RadioSelect
)

MultipleChoiceField - Pick MANY Options

Like checkboxes where you can select multiple.

class ToppingsForm(forms.Form):
    TOPPINGS = [
        ('pepperoni', 'Pepperoni'),
        ('mushrooms', 'Mushrooms'),
        ('onions', 'Onions'),
        ('olives', 'Olives'),
    ]

    toppings = forms.MultipleChoiceField(
        choices=TOPPINGS,
        widget=forms.CheckboxSelectMultiple
    )

TypedChoiceField - Choices with Automatic Type

class RatingForm(forms.Form):
    RATINGS = [
        (1, 'Poor'),
        (2, 'Fair'),
        (3, 'Good'),
        (4, 'Great'),
        (5, 'Excellent'),
    ]

    rating = forms.TypedChoiceField(
        choices=RATINGS,
        coerce=int  # Convert to integer!
    )

📅 Date Form Fields: Working with Time

Like calendar pickers on paper forms.

DateField - Pick a Date

class EventForm(forms.Form):
    # Basic date (YYYY-MM-DD)
    event_date = forms.DateField()

    # With specific format
    birth_date = forms.DateField(
        input_formats=['%d/%m/%Y']  # DD/MM/YYYY
    )

DateTimeField - Date AND Time

class AppointmentForm(forms.Form):
    appointment = forms.DateTimeField()
    # Accepts: 2024-12-25 14:30:00

TimeField - Just Time

class ScheduleForm(forms.Form):
    start_time = forms.TimeField()
    # Accepts: 14:30 or 2:30 PM

DurationField - How Long Something Takes

class TaskForm(forms.Form):
    duration = forms.DurationField()
    # Accepts: "1 day, 2:30:00" or "90:00"

Making Dates User-Friendly

class BookingForm(forms.Form):
    check_in = forms.DateField(
        widget=forms.DateInput(
            attrs={
                'type': 'date',  # HTML5 date picker!
                'class': 'date-picker'
            }
        )
    )

📁 File Form Fields: Uploading Files

Like “attach your resume” on a job application.

FileField - Any File Upload

class ApplicationForm(forms.Form):
    resume = forms.FileField()

    # Optional file
    cover_letter = forms.FileField(required=False)

ImageField - Image Upload Only

Automatically checks if it’s a real image!

class ProfileForm(forms.Form):
    avatar = forms.ImageField()
    # Accepts: .jpg, .png, .gif
    # Rejects: .pdf, .txt

Important! Form Setup for Files

Your HTML form needs special setup:

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
</form>

And in your view:

def upload_view(request):
    if request.method == 'POST':
        form = ProfileForm(
            request.POST,
            request.FILES  # Don't forget this!
        )
        if form.is_valid():
            file = form.cleaned_data['avatar']
            # Now save the file!

File Field Options

class DocumentForm(forms.Form):
    document = forms.FileField(
        help_text="Max 5MB, PDF only",
        widget=forms.FileInput(
            attrs={'accept': '.pdf'}
        )
    )

🎁 Putting It All Together

Here’s a complete, real-world form using everything:

from django import forms

class JobApplicationForm(forms.Form):
    # Common Fields
    full_name = forms.CharField(max_length=100)
    email = forms.EmailField()
    phone = forms.CharField(max_length=20)

    # Choice Fields
    POSITIONS = [
        ('dev', 'Developer'),
        ('design', 'Designer'),
        ('pm', 'Project Manager'),
    ]
    position = forms.ChoiceField(choices=POSITIONS)

    SKILLS = [
        ('python', 'Python'),
        ('js', 'JavaScript'),
        ('design', 'UI/UX'),
    ]
    skills = forms.MultipleChoiceField(
        choices=SKILLS,
        widget=forms.CheckboxSelectMultiple
    )

    # Date Fields
    available_from = forms.DateField(
        widget=forms.DateInput(attrs={'type': 'date'})
    )

    # File Fields
    resume = forms.FileField()
    portfolio = forms.URLField(required=False)

    # Other Common Fields
    years_experience = forms.IntegerField(
        min_value=0, max_value=50
    )
    salary_expectation = forms.DecimalField(
        max_digits=10, decimal_places=2
    )
    agree_to_terms = forms.BooleanField()

🚀 Quick Reference

Field Type Use For Example
CharField Text Names, messages
EmailField Emails user@email.com
IntegerField Numbers Age, quantity
DecimalField Money $99.99
BooleanField Yes/No Checkboxes
ChoiceField Pick one Dropdown
MultipleChoiceField Pick many Checkboxes
DateField Dates 2024-12-25
TimeField Times 14:30
FileField Any file Documents
ImageField Images Photos

🎯 Remember This!

  1. Forms = Smart Paper Forms for the web
  2. Always inherit from forms.Form
  3. Fields auto-validate (email checks, number limits)
  4. is_valid() checks everything
  5. cleaned_data gives you safe, processed data
  6. File uploads need enctype and request.FILES

You now have the power to collect ANY information safely! 🎉


Next up: Form validation, custom widgets, and ModelForms!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.