Django Forms - potatoscript/django GitHub Wiki

๐Ÿ’Œ Django Forms โ€“ Let Users Talk to You

Think of Django Forms as your websiteโ€™s ears and mailbox.
They let people input stuff, and Django knows how to handle it. ๐ŸŽง๐Ÿ“ฎ


๐Ÿช„ What Is a Form?

๐Ÿง’: "Hey website, my name is Lucy!"
๐ŸŒ: "Thanks Lucy, Iโ€™ll save that for you."

Thatโ€™s exactly what a form does.

  • ๐ŸŽจ A form = a bunch of input fields
  • ๐Ÿง  Django handles: validation, security, and data processing
  • โœจ Bonus: it can even save info into the database!

๐Ÿงฑ Two Ways to Build Forms

Method Description Use case
Forms.Form Manual form, field by field Custom input, not tied to models
Forms.ModelForm Auto form from your model Best when saving to DB

Weโ€™ll explore both โ€” letโ€™s go! ๐Ÿƒโ€โ™€๏ธ


๐Ÿ“ฆ Step 1: Create a Simple Form

๐Ÿ“ Inside your app, create a file: forms.py

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

๐Ÿ‘ Boom! You just created a basic form!


๐Ÿ‘๏ธ Step 2: Display It in a View

๐Ÿ“„ In views.py:

from django.shortcuts import render
from .forms import ContactForm

def contact_view(request):
    form = ContactForm()
    return render(request, 'contact.html', {'form': form})

๐Ÿ›ฃ๏ธ In urls.py:

path('contact/', contact_view, name='contact')

๐Ÿง Step 3: Add the Form to the Template

๐Ÿ“„ templates/contact.html

<h2>๐Ÿ“ฌ Contact Us</h2>

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

๐Ÿ” csrf_token = safety shield against bad guys ๐Ÿšซ


๐ŸŽ‰ Step 4: Handle Submitted Data

Update your view:

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            print("Name:", form.cleaned_data['name'])
            print("Email:", form.cleaned_data['email'])
            print("Message:", form.cleaned_data['message'])
    else:
        form = ContactForm()
    
    return render(request, 'contact.html', {'form': form})

๐Ÿง  form.cleaned_data = clean, safe input from the user


๐Ÿ› ๏ธ Bonus: ModelForm (Best for Saving to DB)

Letโ€™s say you have a model:

class Comment(models.Model):
    name = models.CharField(max_length=100)
    message = models.TextField()

๐ŸŽ‰ Now build a form for it:

from django.forms import ModelForm
from .models import Comment

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ['name', 'message']

๐Ÿง This is like automatic cake baking ๐ŸŽ‚ โ€” no need to write all the fields!


Use It in a View

def comment_view(request):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            form.save()  # Automatically saves to database!
    else:
        form = CommentForm()
    return render(request, 'comment.html', {'form': form})

comment.html

<h2>๐Ÿ’ฌ Leave a Comment</h2>

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

๐Ÿ’ก Tips & Tricks

Trick What It Does
{{ form.as_table }} Show form as table
{{ form.as_ul }} Show form as unordered list
widget=forms.PasswordInput() Make password field
required=False Optional input
initial='Hello!' Default text in the field

โœจ Super Example

Letโ€™s build a Feedback Form with rating and emoji! ๐Ÿฅณ

forms.py

class FeedbackForm(forms.Form):
    name = forms.CharField(label="Your Name")
    feedback = forms.CharField(widget=forms.Textarea, label="What do you think?")
    rating = forms.ChoiceField(choices=[(i, f"{i} โญ") for i in range(1, 6)])

views.py

def feedback_view(request):
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
    else:
        form = FeedbackForm()
    return render(request, 'feedback.html', {'form': form})

feedback.html

<h2>๐Ÿ“ Give Us Your Feedback</h2>

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button>Submit Feedback</button>
</form>

๐Ÿ“š Summary Chart

Step Action
โœ… Create form class In forms.py
โœ… Use in view Handle GET/POST
โœ… Show in template Use {{ form.as_p }}
โœ… Handle valid data form.cleaned_data or form.save()

๐Ÿ‘‘ Why Django Forms Are Amazing

โœ… Protects you from hackers
โœ… Validates user input
โœ… Connects to your database
โœ… Easy to style with CSS
โœ… Reusable and clean


๐Ÿ Wrap-Up

Django Forms are your friendly front desk โ€” they receive info, check it, and pass it safely to your system.

Forms make your site interactive, dynamic, and super cool ๐Ÿ˜Ž๐Ÿ’ฌ


โš ๏ธ **GitHub.com Fallback** โš ๏ธ