Django Forms - potatoscript/django GitHub Wiki
Think of Django Forms as your websiteโs ears and mailbox.
They let people input stuff, and Django knows how to handle it. ๐ง๐ฎ
๐ง: "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!
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! ๐โโ๏ธ
๐ 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!
๐ 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')
๐ 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 ๐ซ
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
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!
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})
<h2>๐ฌ Leave a Comment</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Post Comment</button>
</form>
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 |
Letโs build a Feedback Form with rating and emoji! ๐ฅณ
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)])
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})
<h2>๐ Give Us Your Feedback</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button>Submit Feedback</button>
</form>
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()
|
โ
Protects you from hackers
โ
Validates user input
โ
Connects to your database
โ
Easy to style with CSS
โ
Reusable and clean
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 ๐๐ฌ